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.
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)
.