【发布时间】:2021-02-11 19:18:56
【问题描述】:
我是 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'
我做错了什么?
【问题讨论】:
标签: python django django-rest-framework django-simple-history