django - DRF Update Existing Objects -
i'm new drf , python go easy on me... can roadsegment objects, cannot figure out how update existing object
i have 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 following serializer:
class roadsegmentserializer(serializers.hyperlinkedmodelserializer): class meta: model = roadsegment fields = ('entryline','trafficstate','location') and following view
class roadsegmentviewset(viewsets.modelviewset): queryset = roadsegment.objects.all() serializer_class = serializers.roadsegmentserializer my urls.py looks 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 able update existing object
patch http://127.0.0.1:8000/api/v1/roadsegment/
{"entryline":"2nd","trafficstate":"somenewvalue","location":"downtown"}
in view, need provide following:
lookup_field -> id of record want update lookup_url_kwarg -> kwarg in url want compare id of object you need define new url in urls.py file. carry lookup_url_kwarg. can done 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 placed in viewset lookup_url_kwarg.
the request sending is:
patch http://127.0.0.1:8000/api/v1/roadsegment/object_id_to_update/
and done.
Comments
Post a Comment