tags:

views:

35

answers:

2

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(), but 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)
A: 

Team.objects.filter(members__accepted__exact=True)

Take a look at this. It has a lot of great examples and explanations.

Goose Bumper
This doesn't work. I get FieldError: Cannot resolve keyword 'members_accepted' into field. Choices are: id, members, membership
Macha
@Macha: Edited my answer.
Goose Bumper
Still doesn't work. FieldError: Cannot resolve keyword 'accepted' into field. Choices are: date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, membership, message, password, team, user_permissions, username
Macha
@Macha: It looks like the issue is that you have Membership set up as an *intermediary* table; I'm not sure how a query for that would work. This might help you: http://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomanyThe above query works fine for me if I set up the models without creating Membership as an intermediary table, like so:http://www.pastie.org/878744
Goose Bumper
+1  A: 

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.

istruble