如何通过ManyToMany关系获取django模型?

时间:2013-07-07 05:48:16

标签: django model many-to-many

我得到了Player个实例(一个团队)的列表,例如team = [player1, player2, player3]

如何通过一个查询“get_or_create”包含这些且只有这三个玩家的Team

这些是我的django模型:

class Player(models.Model):
    name = models.CharField(max_length=100)

class Team(models.Model):
    players = models.ManyToManyField(Player)

1 个答案:

答案 0 :(得分:1)

文档说明get_or_create是以下的快捷方式:

try:
    obj = Person.objects.get(first_name='John', last_name='Lennon')
except Person.DoesNotExist:
    obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
    obj.save()

所以我会根据你的用例进行调整,如下所示:

from django.db.models import Q, Count
import operator

players = [player1, player2, player3]

team = Team.objects
    .filter(reduce(
         operator.and_,
         [Q(players=player) for player in players]
    ))
    .annotate(count=Count('players'))
    .filter(count=len(players))

# Note that this ^ returns a QuerySet. With your posted model there
# might exist several teams with exactly the same players.  

if not team.exists():
    team = Team.objects.create()
    team.players.add(*players)

稍微复杂但工作流程是相同的:

  • 查询存在。
  • 如果不存在,请创建。