Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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)
>>> 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")
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 questionAsk a Question
731 491 924 answers to any question