I'm working on an app that currently has a lot of ManyToMany relationships (and will eventually have even more), and I'm trying to think of clever ways (read: the right ways) to accurately query the ORM for JOINed data.
Here's a sample of what I have and what I need to do. I apologize for the pseudocode.
ProjectModel:
owner = ForeignKey(User) #just one user
people = ManyToMany(User) #multiple users and theoretically can also contain the owner
Now what I want to query is a list of every User who is a "people" in projects that the Current User owns.
I have no real clue how to do this. __contains doesn't really seem suited for this... so I think my options are basically down to just queryin开发者_如何学Cg every project and doing the iterations myself. But it would be much more enriching if I knew how to get this via ORM/SQL.
Thanks!
# users in projects owned by request.user
users = User.objects.filter(projectmodel__owner=request.user).distinct()
If there are a lot of m2ms, and you had defined a related_name
in your people
field, that's what you would use in your reverse lookup instead of projectmodel
.
精彩评论