简体   繁体   中英

How to add points to an IntegerFiedl with serializer DRF

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM