文檔中說,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個查詢? –