ドキュメンテーションによると、それ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)
少し複雑ですが、ワークフローは同じです。
- 存在を照会します。
- 存在しない場合は、作成します。