我有几个简单的模型,通过模型建立了M2M关系(为了清晰起见,删除了关系中的额外数据):
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)
如果我想让所有与团队相关联的社区,我知道我可以先通过m2m字段获取社区的ID,然后使用该列表过滤社区:
communities = Community.objects.filter(id__in=team.communities.all().values_list('community_id', flat=True)
这感觉不必要地繁琐,我想知道是否有一种更惯用的方式来在一个声明中为团队提供社区,而不首先查询ID
(伪代码)
communities = team.communities.all().values_list('community') # this returns ths ids of the communities, not the whole Community model
答案 0 :(得分:1)
如果我想让所有与团队相关的社区
#you just need to use the M2M field
communities = team.communities.all()
#If you want CommunityMemberships instead
community_memberships = team.communitymembership_set.all()