Andrés Root
Andrés Root

Reputation: 642

Django Rest Framework: After adding related field with serializer I get Integrity error

I had the following serializer. Django Rest Framework allows me to create, update, delete and get info just with this code. Of course I'm adding the serializer to the viewset but the problem is not there:

class MeasurmentSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Measurment
        fields = ('id', 'user_statistic', 'value', 'date_created')

I needed to add the detailed info for the field "user_statistic" whenever I GET the data, not just the URL so I added the code in second line and it worked, I got the extra info I needed:

class MeasurmentSerializer(serializers.HyperlinkedModelSerializer):
    user_statistic = UserStatisticSerializer(read_only=True) # New Code Added

    class Meta:
        model = Measurment
        fields = ('id', 'user_statistic', 'value', 'date_created')

However the when I POST to the API to create new info into the database it shows the following error:

NotNullViolation: null value in column "statistic_id" of relation "cms_userstatistic" violates not-null constraint DETAIL: Failing row contains (55, 6, 0, f, f, null, 2022-01-05, 2022-01-05, null, 67).

It seems that serializing a related field prevents DRF to get the related field info whenever it tries to create a new object. How can I add the detailed info for that specific related field without breaking the POST request? I wonder if there is another way of getting this info without using the function "to_representation" that allows me to customize the resulting object.

I thank you all for any clue you can give me.

Upvotes: 0

Views: 1203

Answers (1)

Yevhenii Kosmak
Yevhenii Kosmak

Reputation: 3860

Just serialize your user_statistic into the other field:

from rest_framework import serializers

# ...

class MeasurmentSerializer(serializers.HyperlinkedModelSerializer):
    user_statistic_detailed = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Measurment
        fields = ('id', 'user_statistic', 'value', 'date_created', 
                  'user_statistic_detailed')

        def get_user_statistic_detailed(self, record):
            return serialize(UserStatisticSerializer, record.user_statistic)

Upvotes: 1

Related Questions