[Answered ]-Update multiple resource together in Django DRF

1👍

For this scenario, you can use django transaction which will rollback your database transaction if any error occur in your transaction block. Something Like this-

from django.db import transaction

with transaction.atomic():
    Inventory.objects.create(**kwargs)
    InventoryProperties.objects.create(**kwargs)

In the transaction block, if saving InventoryProperties gives any error then Inventory Table will be rollback.

0👍

Seems like InventoryProperties entity will never use without their Inventory relation. So, you can use JSONField Inventory.propetries instead of separate entity.

class Inventory(models.Model):
    props = models.JSONField(default=list)
    name = models.CharField(max_length=100, unique=True)


class InventorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Inventory
        fields = ['name', 'props']

This serializer would rewrite all props on every save in 1 SQL UPDATE query. As a bonus, you don’t need to support InventoryProperties.order field.

Input example

{
   "name": "inv1",
   "props": [
      {"key": "size", "value": 30},
      {"key": "weight", "value": 16},
   ]
}

Also, you can add method to access your propetries by key

class Inventory(models.Model):
    def get_prop(self, key: str):
        for prop in self.props:
            if prop["key"] == key:
                return prop["value"]
        return None
       

If you want to add validation of JSON you can use this approach

0👍

The solution for me was that I created a separate endpoint where I can update nested and multiple models at the same time, while providing typical RESTful endpoints also.
This endpoint uses atomic transaction so that if anything goes wrong in the business logic, nothing gets committed.

Leave a comment