Hi!
I want to optimize the following into a single SQL statement.
I am not sure even if it is possible or not.
I know I can do it in a single transcation with transaction.atomic but not sure how i can do it in a single SQL statement.
try:
user = User.objects.get(pk=user_id)
except User.DoesNotExist:
pass
try:
toy = Toy.objects.get(pk=toy_id)
except Toy.DoesNotExist:
pass
try:
ToyRole.objects.create(toy=toy, user=user, role=ToyRole.OWNER)
except Exception as e:
pass
unowned_toyparts = toy.toy_parts.filter(user_roles__user_isnull=True)
for t in unowned_toyparts:
try:
ToyPartUserRole.objects.create(toy_part=t, user=user, role=ToyPartUserRole.OWNER)
except Exception as e:
pass
Here ToyRole
and ToyPartRole
are through tables associated with Toy and ToyPart models respectively.
Thanks in advance