文档中说,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)
略微复杂但工作流程相同:
这个答案应该让你回到正轨 http://stackoverflow.com/questions/5301996/django-many-to-many-query –
我正在回答的权利,但它可能需要一段时间才能真正发布。 –
你知道,即使你只需要调用'get_or_create'这将是2个查询? –