【问题标题】:DRF Update Existing ObjectsDRF 更新现有对象
【发布时间】:2015-06-14 20:17:40
【问题描述】:

我是 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"}]

我希望能够更新现有对象

补丁http://127.0.0.1:8000/api/v1/roadsegment/

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

【问题讨论】:

标签: django django-rest-framework


【解决方案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 放置在您的视图集中。

您现在要发送的请求是:

补丁http://127.0.0.1:8000/api/v1/roadsegment/object_id_to_update/

你就完成了。

【讨论】:

  • 谢谢!我能够让它与这些信息一起工作。由于某种原因,url 必须在 urlpatterns 中,而不是在路由器中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-21
  • 2018-02-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多