2

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

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

这些是我的 Django 模型:

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

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

1 回答 1

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)

稍微复杂一点,但工作流程是一样的:

  • 查询存在。
  • 如果不存在,则创建。
于 2013-07-07T10:24:57.913 回答