Optimize Django ORM into a single SQL statement?

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

The facilities that various database vendors provide to permit updating multiple tables in one SQL statement are all extensions to the SQL standard, and generating code for such would not be compliant with the appropriate standards. You’d have to write an extension to create some syntax allowing you do do that in the ORM, then you’d still have to provide a way for Django to break that up into separate update statements for databases not providing that facility.

There are no vendors that I’m aware of that allow inserting data into multiple tables in a single SQL statement.

You could probably create a stored procedure in the database to effectively provide that facility, but I’m not sure I understand why one would bother doing that. (Any claims of it being an “optimization” would need to be able to prove that it actually is one.)