简体   繁体   English

Django rest-framework:如何让客户端知道pk,以便它可以获取,更新或删除

[英]Django rest-framework:How to let client know the pk so that it can get,update or delete

django rest framework Django Rest框架

I have two api 我有两个API

url(r'^testall/$',views.DataList.as_view()),
url(r'^testone/(?P<pk>[0-9]+)/$',views.DataDetail.as_view()),

I have a question ,the r'^testone/(?P<pk>[0-9]+)/$ url can get , update ,and delete 我有一个问题, r'^testone/(?P<pk>[0-9]+)/$ url可以getupdatedelete

But the user have to know the pk 但是用户必须知道pk
How can I let client know the pk is ?? 我如何让客户知道pk是??

views.py views.py

class DataList(generics.ListCreateAPIView):
    queryset = Data.objects.all()
    serializer_class = DataSerializer
class DataDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Data.objects.all()
    serializer_class = DataSerializer

This is my models 这是我的models

class Data(models.Model):

    mac_address = models.CharField(max_length=50, null=False, blank=False)
    datetime = models.DateTimeField(auto_now=False, auto_now_add=False)
    ...

I have a field mac_address ,which is unique and the client know that 我有一个字段mac_address ,这是唯一的,客户端知道
I think maybe I can edit code to 我想也许我可以编辑代码来

 url(r'^testone/(?P<mac_address>\w+)/$',views.DataDetail.as_view())

But I got error: 但是我得到了错误:

Expected view DataDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.   

And I'm not sure use the mac_address with : in url ( http://localhost:8000/test/A1:BC:34:WD:TT/ ) is a good idea Please guide me 而且我不确定在URL( http://localhost:8000/test/A1:BC:34:WD:TT/ )中使用带:mac_address是一个好主意,请指导我
Thank you very much 非常感谢你

Here pk is lookup_field, when you call this url, url(r'^testall/$',views.DataList.as_view()) you will get response like 这里的pk是lookup_field,当您调用此URL url(r'^testall/$',views.DataList.as_view())您将获得如下响应

{'id': 4, 'mac_address': 3423, ..}

, here "id" is the "pk" This id can be used for calling ,这里的“ id”是“ pk”

url(r'^testone/(?P<pk>[0-9]+)/$',views.DataDetail.as_view()),

And In views you can use mac_address as lookup_field, 在视图中,您可以将mac_address用作lookup_field,

url(r'^testone/(?P<mac_address>\w+)/$',views.DataDetail.as_view())

class DataDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Data.objects.all()
    serializer_class = DataSerializer
    lookup_field = 'mac_address'

You can refer more http://www.django-rest-framework.org/api-guide/generic-views/#genericapiview 您可以参考更多http://www.django-rest-framework.org/api-guide/generic-views/#genericapiview

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM