Canute Bigler
Canute Bigler

Reputation: 220

Idiomatic way to get related model list

I've got a couple of simple models, with an M2M relationship through a model (extra data on relationship removed for clarity):

class Team(models.Model):
    name = models.CharField(max_length=200)
    communities = models.ManyToManyField(Community, through='CommunityMembership')

class Community(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()

class CommunityMembership(models.Model):
    team = models.ForeignKey(Team)
    community = models.ForeignKey(Community)

If I want to get all of the communities associated with a team, I know I can first get the ids of the communities through the m2m field and then use that list to filter the Communities:

communities = Community.objects.filter(id__in=team.communities.all().values_list('community_id', flat=True) 

This feels unnecessarily cumbersome and I'd like to learn if there is a more idiomatic way to get just the communities for a team in a single statement without first querying the ids

(pseudocode)

communities = team.communities.all().values_list('community') # this returns ths ids of the communities, not the whole Community model

Upvotes: 0

Views: 31

Answers (1)

Todor
Todor

Reputation: 16020

If I want to get all of the communities associated with a team

#you just need to use the M2M field
communities = team.communities.all()

#If you want CommunityMemberships instead
community_memberships = team.communitymembership_set.all()

Upvotes: 1

Related Questions