1

Assuming I have 2 models, one User, the other Post. A user can create posts. A user has a field called 'exp_pts' as an IntegerField. This is meant to increment by say 30 when the user creates a post.

I assume I would have to use the create() method in the PostSerializer. This is my current serializer for Posts (currently not working due to the create() method not working as intended)

class PostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Post
        fields = ('id', 'user', 'kingdom', 'post_type', 'file_path',
                  'title', 'description', 'created_at', 'updated_at')

    def to_representation(self, instance):
        data = super().to_representation(instance)
        data['user'] = SimpleUserSerializer(
            User.objects.get(pk=data['user'])).data
        data['kingdom'] = KingdomSerializer(
            Kingdom.objects.get(pk=data['kingdom'])).data
        return data

    # This is not yet working
    def create(self, validated_data):
        user = validated_data.pop('user')
        user.exp_pts += 30
        user.save()
        return user

What is a way to do the above? If the create() method isn't adequate then what other way is there to achieve this? Any help much appreciated. Thank you.

1 Answer 1

2

Your create method is wrong. It should be more like that:

def create(self, validated_data):
        user = validated_data.pop('user')
        user.exp_pts += 30
        user.save()

        return super().create(validated_data)

Your serializer's create method has to return an instance of the created Post, not User. Since the actual creation can be handled by DRF itself, just return super().create(validated_data).

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the comment, I see what you mean, however this is still giving this error:django.db.utils.IntegrityError: NOT NULL constraint failed: api_post.user_id
ah, your post model has a user FK. then dont pop the the user from the dict, but get it.
replacing 'pop' with 'get' did it. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.