我是 Python、Django 和 DRF 的新手,但我已经阅读了设置基本 REST 服务器所需的所有教程,对于这个示例,我们假设它只服务一件事:客户列表。此外,我已经安装django-simple-history
并注册了我的Customer
模型。
这是我迄今为止编写的代码,一切似乎都运行良好。
api/urls.py
from django.urls import path, include
from rest_framework import routers
import api.views as views
router = routers.DefaultRouter(trailing_slash=False)
router.register('customers', views.CustomerView)
router.register('customerhistory', views.CustomerHistoryView)
urlpatterns = [
path('', include(router.urls)),
]
api/views.py
from rest_framework import viewsets
from retail.models.customers import Customer
class CustomerView(viewsets.ModelViewSet):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
filterset_fields = '__all__'
search_fields = ['name']
class CustomerHistoryView(viewsets.ModelViewSet):
queryset = Customer.history.all()
serializer_class = CustomerHistorySerializer
filterset_fields = '__all__'
api/serializers.py
from rest_framework import serializers
from retail.models.customers import Customer
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model = Customer
fields = '__all__'
class CustomerHistorySerializer(serializers.ModelSerializer):
class Meta:
model = Customer.history.model
fields = '__all__'
实际上,当我转到 时api/customerhistory/1
,它为我提供了客户 1 的所有历史记录的可爱列表。
问题
我想要做的是访问相同的列表api/customer/1/history
。
到目前为止我的尝试...
为此,我将删除CustomerHistoryView
并在类中添加额外的操作CustomerView
。
api/views.py
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
from retail.models.customers import Customer
class CustomerView(viewsets.ModelViewSet):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
filterset_fields = '__all__'
search_fields = ['name']
@action(detail=True)
def history(self):
history = Customer.history.all()
serializer = CustomerHistorySerializer(history, many=True)
return Response(serializer.data)
这会产生以下错误:
Exception Type: TypeError at /api/customers/1/history
Exception Value: history() got multiple values for argument 'pk'
我究竟做错了什么?