Kevin
Kevin

Reputation: 28

DRF Update Existing Objects

I'm new to DRF and python so go easy on me... I can successfully get the RoadSegment objects, but I cannot figure out how to update an existing object

I have the following model:

class RoadSegment(models.Model):
   location = models.CharField(max_length=100)
   entryline = models.CharField(unique=True, max_length=100)
   trafficstate = models.CharField(max_length=100)

With the following serializer:

class RoadSegmentSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = RoadSegment
        fields = ('entryline','trafficstate','location')

And the following view

class RoadSegmentViewSet(viewsets.ModelViewSet):
    queryset = RoadSegment.objects.all()
    serializer_class = serializers.RoadSegmentSerializer

My urls.py looks as follows:

router.register(r'roadsegment', RoadSegmentViewSet, base_name='roadsegment-detail')

GET http://127.0.0.1:8000/api/v1/roadsegment/ returns

[{"entryline":"2nd","trafficstate":"main","location":"downtown"},{"entryline":"3nd","trafficstate":"low","location":"downtown"}]

I would like to be able to update an existing object

PATCH http://127.0.0.1:8000/api/v1/roadsegment/

{"entryline":"2nd","trafficstate":"SOMENEWVALUE","location":"downtown"}

Upvotes: 0

Views: 1123

Answers (1)

Animesh Sharma
Animesh Sharma

Reputation: 3386

In your view, you need to provide the following:

lookup_field -> Most probably the ID of the record you want to update 
lookup_url_kwarg -> The kwarg in url you want to compare to id of object

You need to define a new url in your urls.py file. This will carry the lookup_url_kwarg. This can be done as follows:

urlpatterns = patterns('',
    url(r'^your_url/$', RoadSegmentViewSet.as_view()),
    url(r'^your_url/(?P<kwarg_name_of_your_choice>\w+)/$',RoadSegmentViewSet.as_view()),
)

kwarg_name_of_your_choice needs to placed in your viewset as lookup_url_kwarg.

The request that now you would be sending is:

PATCH http://127.0.0.1:8000/api/v1/roadsegment/object_id_to_update/

And you are done.

Upvotes: 2

Related Questions