These are the (pseudo) models I’ve got.
Blog:
name
etc...
Article:
name
blog
creator
etc
User (as per django.contrib.auth)
So my problem is this: I’ve got two users. I want to get all of the articles that the two users published on the same blog (no matter which blog). I can’t simply filter the Article model by both users, because that would yield the set of Articles created by both users. Obviously not what I want. but can I filter somehow to get all of the articles where a field of the object matches between the two querysets?
This is a great question for exercising Django’s ORM 🙂
Depending on which parameters are known in advance, there are a couple ways to approach this.
Scenario 1: You know the users and the specific blog
If you have one particular blog in mind and want to simple find all articles written by either author, you can use a Q object. I don’t think this is your scenario, but I’ll put it here just in case:
Scenario 2: You know only the users
If you want to find all blogs where both users have published, and want to then find which articles they’ve published in those blogs, you’d want to start from the
Blogmodel:Edit based on Paulo’s comments:
Here is a test set of models that I believe matches the OP’s pseudo code and which demonstrates the above code working (at least on sqlite3 and postgres):
Then some data where both user1 and user2 write articles on blog2:
The query:
produces:
And the SQL is (my test django app was named foo):
So, while the
WHEREclause does have(A AND B),AandBreference different inner joins ("foo_article"."creator_id"vs.T4."creator_id"), and not the same table (which is what filter(A, B) would generate, (ie:WHERE ("foo_article"."creator_id" = 1 and "foo_article"."creator_id" = 2))(Without the
distinct()clause, if you added more articles for either author, you’d get multipleb2entries in the queryset results.)Like I said, it’s a great ORM exercise!