DRF url 路由与通用视图 RetrieveUpdateAPIView 不匹配

DRF url route did not match for genericview RetrieveUpdateAPIView

我已将以下路由添加到我的 Django Rest 框架项目中,url 匹配良好,returns 订单和库存的列表视图但它与详细视图不匹配 order/<int:order_no>inventory/<int:pk>

localhost:8000/FD/orders/ 工作但是 localhost:8000/FD/order/1/与returns

不匹配
Using the URLconf defined in FriendsDigital.urls, Django tried these  
URL patterns, in this order:  
 
1. admin/  
2. ^rest-auth/  
3. ^FD/ ^inventories/$ [name='inventory_list']   
4. ^FD/  ^inventory/<int:pk>/ [name='inventory_edit']  
5. ^FD/ ^orders/ [name='orders_list']  
6. ^FD/ ^order/<int:order_no>/ [name='order_update']  

The current path, FD/order/1/, didn't match any of these

同样的问题是库存

Urls.py

urlpatterns = [
    url('^inventories/$', InventoryList.as_view(), name='inventory_list'),
    url('^inventory/<int:pk>/', InventoryRetrieveUpdate.as_view(), name='inventory_edit'),
    url('^orders/', BusinessOrderList.as_view(), name='orders_list'),
    url('^order/<int:order_no>/',BusinessOrderUpdate.as_view(), name='order_update')
]

views.py

class InventoryList(generics.ListAPIView):
    queryset= Inventory.objects.all()
    serializer_class = InventorySerializer

class InventoryRetrieveUpdate(generics.RetrieveUpdateAPIView):
    queryset = Inventory.objects.all()
    serializer_class = InventorySerializer

class BusinessOrderList(generics.ListCreateAPIView):
    queryset = BusinessOrder.objects.all()
    serializer_class = BusinessOrderSerializer

class BusinessOrderUpdate(generics.RetrieveUpdateAPIView):
    queryset = BusinessOrder.objects.all()
    serializer_class = BusinessOrderSerializer

Django 版本 - 3.0.7 DjangoRestFramework - 3.11.0

DRF 查找字段默认为 'pk',因此您必须手动指定 lookup_fields:

class BusinessOrderUpdate(generics.RetrieveUpdateAPIView):
    queryset = BusinessOrder.objects.all()
    serializer_class = BusinessOrderSerializer
    lookup_field = 'order_no'

您需要使用 path if you want to use the angle bracket notation (<int:order_no>) for your urls. The url 函数是 re_path 的别名,它使用正则表达式

from django.urls import path

urlpatterns = [
    ...
    path('order/<int:order_no>/', BusinessOrderUpdate.as_view(), name='order_update')
]