Issue
I've got serializer like this and each time i do Put on that url, i want the number_of_points increase(+=1), but now when i do it, it stays the same and doesnt change. Do you have any idea how to fix it?
class Answer(models.Model):
number_of_points = models.IntegerField(default=0)
class AddPointsSerializer(serializers.ModelSerializer):
class Meta:
model = Answer
fields = ('number_of_points',)
def update(self, instance, validated_data):
instance.number_of_points += 1
return instance
class AddPointsAnswer(generics.UpdateAPIView):
queryset = Answer.objects.all()
serializer_class = AddPointsSerializer
def get_queryset(self):
return super().get_queryset().filter(
id=self.kwargs['pk']
)
path('answers/<int:pk>/addpoints', AddPointsAnswer.as_view()),
Solution
def update(self, instance, validated_data):
instance.number_of_points += 1
return instance
Add instance.save()
to this function. You're updating the attribute on the model instance, but never saving it to the database.
Answered By - jorf.brunning
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.