hackerman
hackerman

Reputation: 1291

Updating a model using Django Rest Framework and ViewSets

I'm new to DRF, and I'm trying to build a webhook that gives out lists of model objects and also allows these objects to be updated. I followed this tutorial http://www.django-rest-framework.org/tutorial/quickstart/, and have the following serializer and view:

class Task(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ('user', 'task', 'unixTime')

View:

class RequestViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows reqests to be viewed or edited.
    """
    queryset = Task.objects.filter(done = False).order_by('-unixTime')
    serializer_class = Task
    paginate_by = None

    def list(self, request, *args, **kwargs):
        self.object_list = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(self.object_list, many=True)
        return Response({'results': serializer.data})

I'm pretty sure I have to include a def update under def list, but the online resources I found were a bit unclear on how to implement them and what they do. Any help is appreciated.

Upvotes: 1

Views: 3125

Answers (2)

gzerone
gzerone

Reputation: 2227

@hackerman, Hmm..., if you followed the next step,

http://www.django-rest-framework.org/tutorial/quickstart/#urls

You will get an api address, it may looks like http://localhost:8000/task/1/, assume here is a task obj (id=1) in your db. Please open it in your browser and check that api works or not.

And then, you need a http client (requests is a good choice) to create a PUT request with json string data.

Hope those can help.

Upvotes: 3

user8060120
user8060120

Reputation:

May be you just need to rename the serializer.

class TaskSerializer(serializers.ModelSerializer):

And don't forget replace in the viewset

serializer_class = TaskSerializer

After it you can remove your list method, because it is standard.

Upvotes: 2

Related Questions