首页 > 解决方案 > 更改 URL 对 JSON 返回的 DjangoRest 框架没有影响

问题描述

我正在尝试过滤存储的客户列表并在尝试时返回一个特定的客户 (xxx/api/customers/fred) 它返回所有客户以及在客户之后输入的任何内容/对返回的 JSON 没有影响

意见

class CustomerListAPIView(generics.ListAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer

class CustomerRetrieveAPIView(generics.RetrieveAPIView):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer
    lookup_field= "name"

序列化器

class CustomerSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Customer 

        fields = ['name' , 'address', 'phonenumber']

网址

url(r'^api/customers/', views.CustomerListAPIView.as_view(), name = "customer_list"),
url(r'^(?P<slug>[\w-]+)/$', views.CustomerRetrieveAPIView.as_view(), name='retrieve'),

我还尝试覆盖 def get_queryset(self, *args, **kwargs): 但是当输入 url 时这个方法似乎没有被触发

标签: djangodjango-modelsdjango-rest-frameworkdjango-urls

解决方案


将更详细的 url 放在更通用之前以避免歧义,将 $ 添加到customer_listURL 模式的末尾,将缺少的前缀添加到retrieveURL 模式:

url(r'^api/customers/(?P<slug>[\w-]+)/$', views.CustomerRetrieveAPIView.as_view(), name='retrieve'),
url(r'^api/customers/$', views.CustomerListAPIView.as_view(), name = "customer_list"),

您的所有请求都由第一个模式处理 - 因为(列表和详细信息)URL 都以api/customers/.


推荐阅读