Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

additional conditions on join in django [duplicate]

Tags:

python

django

Is it possible to add an additional condition to join statement created by django ORM?

What I need in SQL is

'SELECT "post"."id", COUNT("watchlist"."id") FROM "post"   LEFT OUTER JOIN "watchlist"      ON ("post"."id" = "watchlist"."post_id" AND "watchlist"."user_id" = 1)   WHERE "post"."id" = 123  GROUP BY … 

In django most of this is

Post.objects.annotate(Count('watchinglist')).get(pk=123) 

But how can I add AND "watchlist"."user_id" = … into JOIN condition with django ORM?

Adding it to filter fails to get Post objects with no associated objects in watchlist.

like image 354
HoverHell Avatar asked Jul 25 '10 08:07

HoverHell


Video Answer


1 Answers

In Django v2.0 use FilteredRelation

Post.objects.annotate(     t=FilteredRelation(         'watchlist', condition=Q(watchlist__user_id=1) ).filter(t__field__in=...) 
like image 99
Charmy Avatar answered Sep 19 '22 05:09

Charmy