DRF更新现有对象

时间:2015-06-14 20:17:40

标签: django django-rest-framework

我是DRF和python的新手,所以对我很轻松......我可以成功获取RoadSegment对象,但我无法弄清楚如何更新现有对象

我有以下型号:

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

使用以下序列化程序:

class RoadSegmentSerializer(serializers.HyperlinkedModelSerializer):

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

以下视图

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

我的urls.py看起来如下:

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

GET http://127.0.0.1:8000/api/v1/roadsegment/返回

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

我希望能够更新现有对象

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

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

1 个答案:

答案 0 :(得分:1)

在您看来,您需要提供以下内容:

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

您需要在urls.py文件中定义新网址。这将带有lookup_url_kwarg。这可以按如下方式完成:

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需要放在您的视图中lookup_url_kwarg

现在要发送的请求是:

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

你已经完成了。