文档说这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)
稍微复杂一点,但工作流程是一样的: