I
I
iegor2016-04-08 17:47:29
Django
iegor, 2016-04-08 17:47:29

How to form left outer join in orm?

You need to make a simple request:

S.objects.raw('select app_s.name, app_t.name as t from app_s LEFT OUTER JOIN app_t ON app_s.id=app_t.s_id')
### где у t внешний ключ к s

Is it possible using standard Django ORM?
Task: select all s, t, if there is no t for given s, get s, None, the reverse situation is impossible.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem Klimenko, 2016-04-08
@iegor

class S(models.Model):
    name = models.CharField(max_length=255, verbose_name='Название')


class T(models.Model):
    name = models.CharField(max_length=255, verbose_name='Название')
    s = models.ForeignKey(S)

Option 1
>>> print(S.objects.all().values('name', 't__name').query)
SELECT "core_s"."name", "core_t"."name" FROM "core_s" LEFT OUTER JOIN "core_t" ON ("core_s"."id" = "core_t"."s_id")

Option 2
print(S.objects.all().annotate(t_name=F('t__name')).query)
SELECT "core_s"."id", "core_s"."name", "core_t"."name" AS "t_name" FROM "core_s" LEFT OUTER JOIN "core_t" ON ("core_s"."id" = "core_t"."s_id")
# тут на выходе будут экземпояры модели S, но стоит учитывать что при таком запросе они могут дублироваться для разных значений t.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question