Reputation: 593
I want to make a Survey Api for a school with the name of the teachers with Dango-Rest-Framework. I want to create a way so users can post the name of the teacher (or the id of the teacher in Teacher model) and automatically add one point to that teacher's point field.
Here is my Teacher Model class:
class Teacher(models.Model):
name = models.CharField(max_length=255)
description = models.TextField(blank=True,null=True)
voting = models.IntegerField(default=0)
and views.py:
class TeachersViewSet(viewsets.ModelViewSet):
queryset = models.Teachers.objects.all()
serializer_class = serializers.TeachersSerializer
authentication_classes = (TokenAuthentication,)
so what i want is that on the frontend users can call the api and tell that add 1 point the this teacher's voting field(they don't need to metion the number 1. because the api always has to add 1 point for each request).Do I have to create a new Viewset? Honestly I don't know where to start; so any help would be appreciated.
Upvotes: 0
Views: 3949
Reputation: 2291
Expose the ViewSet's Update method
as an API which takes in the teacher id and adds one to its vote
Override update
method.
class TeachersSerializer(ModelSerializer):
def update(self, instance, validated_data):
instance.vote += 1
instance.save()
return instance
Upvotes: 1
Reputation: 2830
Check out DRF's routing for extra actions. I find it super useful. In your case, you could add something like this:
class TeachersViewSet(viewsets.ModelViewSet):
...
@action(detail=True)
def vote(self, request, pk=None):
Teacher.objects.filter(pk=pk).update(voting=F('voting') + 1)
return Response()
Assuming you are using DRF's standard routing, this would serve up a url along the lines of /api/teachers/[id]/vote
. Of course, lots of modifications from here, but this is a starting point.
Upvotes: 3