I have the following models in my Django app. How can I from the Team
model find all the User
objects who have accepted as True in the Membership model? I know I need to use Team.objects.filter()
, bu开发者_StackOverflow社区t I'm not sure how to check the value of the accepted
field.
from django.contrib.auth.models import User
class Team(models.Model):
members = models.ManyToManyField(User, through="Membership")
class Membership(models.Model):
user = models.ForeignKey(User)
team = models.ForeignKey(Team)
accepted = models.BooleanField(default=False)
Accepted members of a team:
team_42.members.filter(membership__accepted=True)
Teams user alice
has been accepted by:
alice.team_set.filter(membership__accepted=True)
I believe you want to get the set of Team or User objects and not the set of intermediate Membership objects. You answered the question yourself but with an answer that gives the set of Membership objects.
Team.objects.filter(members__accepted__exact=True)
Take a look at this. It has a lot of great examples and explanations.
精彩评论