Home > Enterprise >  serializer method to set the value of an attribute doesn't work in a post request. I am using D
serializer method to set the value of an attribute doesn't work in a post request. I am using D

Time:12-13

I have a model which has an attribute "transaction_id" which is a customized ID field and it's value has to be calculated in order to be saved in the database.

I have a model:

class Transaction(models.Model):
     field = models.IntegerField(default=0)
     transaction_id = models.UUIDField(unique=True)

This is the seriaizer:

class TransactionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Transaction
        fields = '__all__'
        read_only_fields = ['id', 'transaction_id']

    def set_tn_number(self):
        tn_number = "some_string/"
        #I have to perform some calculation in order to get the relevant value
        tn_number = tn_number   str(10)
        return tn_number

Now in my post method of the view, i am performing the following:

def post(self, request):
        serializer = TransactionSerializer(data=request.data)
        if serializer.is_valid():
            serializer.tn_number = serializer.set_tn_number()
            serializer.save()
            message = {'message': "Transaction Created Successfully"}
            return Response(message, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

But i am still getting integrity error:

NOT NULL constraint failed: transaction_transaction.transaction_id

Can someone please help me with this?

Thank you for your time

CodePudding user response:

Update validated data or pass the necessary model attributes to save method as kwargs.

def post(self, request):
    serializer = TransactionSerializer(data=request.data)
    if serializer.is_valid():
        tn_number = serializer.set_tn_number()
        serializer.save(transaction_id=tn_number)
        message = {'message': "Transaction Created Successfully"}
        return Response(message, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  • Related