django - 更改 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 时这个方法似乎没有被触发
解决方案
将更详细的 url 放在更通用之前以避免歧义,将 $ 添加到customer_list
URL 模式的末尾,将缺少的前缀添加到retrieve
URL 模式:
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/
.
推荐阅读
- php - php dom 输出中的问题
- swift - TextAlignmentStyle .natural 不适用于 SwiftUI
- r-lavaan - 二阶 CFA (lavaan) 测量智能的控制变量
- python - 如何在三引号输入中输入整数?
- c# - 使用 vs2019 构建 xamarin.forms 4.8 nuget 包时出现构建错误 XliffTasks not found
- python - 在 Python 中创建空的二维数组?
- azure-data-explorer - 循环遍历表格表达式并为 KUSTO 中的每一行运行子查询
- android - Android Studio中带有延迟的平滑拖动效果
- components - 在 SAPU15 中选择数据绑定
- c - 客户端连接但不发送数据怎么办?