tags:

views:

71

answers:

2

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 dhango ORM?

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

+1  A: 
Post.objects.annotate(Count('watchinglist')).filter(pk=123).extra(where=['"watchlist"."user_id" = 1'])

Happy Coding.

simplyharsh
Looks like it acually does the same thing as filter(). E.g. adding one parameter to WHERE, not to ON, and, therefore, providing empty result if there's no watchinglist object.
But, actually, good idea. I missed the 'extra' parameter of Count. Looks like that one works.
...or maybe not. 'extra' there seems to have somewhat different purpose.
A: 

I found a similar question here: http://stackoverflow.com/questions/256325/django-filtering-on-related-objects

And, looks like there's no way to do it without custom SQL.