Home > front end >  Django Rest Framework, How to update nested values in serializer
Django Rest Framework, How to update nested values in serializer

Time:12-20

In DRF, I would like to post bulk transactions to my rest endpoint.

On the following Serializer what would be the correct way to create a nested field of values for transactions in DFR?

Do you call create for each transaction on TransactionItemSerializer

OR

Call save() on the Transaction model inside MasterSerializer create myself>

For example:

class MasterSerializer(serializers.Serializer):

    transactions = TransactionItemSerializer(many=True)  # A nested list of 'transaction' items.

1 . Update transactions on MasterSerializer.

def create(self, validated_data):
    transactions = validated_data.pop('transactions')
    # for each transaction do Transaction Save()

2 . Somehow call the create method of the TransactionItemSerializer within MasterSerializer create method for each transaction i.e

  class MasterSerializer(serializers.Serializer):

    transactions = TransactionItemSerializer(many=True)
    
    class Meta:
        fields = ['transactions']

    def create(self, validated_data):
        transactions = validated_data.pop('transactions')
        # call create on for each transaction TransactionItemSerializer.create() here

CodePudding user response:

Assuming your model name is 'Transaction' and it has 'master' field referencing a master transaction, you can do:

def create(self, validated_data):
    transactions = validated_data.pop('transactions', [])
    instance = super().create(validated_data)

    for transaction in transactions:
        Transaction.objects.create(master=instance, **transaction)

    instance.refresh_from_db()
    return instance
  • Related