Home > Blockchain >  How to add points to an IntegerFiedl with serializer DRF
How to add points to an IntegerFiedl with serializer DRF

Time:02-04

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()),

CodePudding user response:

    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.

  •  Tags:  
  • Related