我得到了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)
答案 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)
稍微复杂但工作流程是相同的: