作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我将在 Django 中使用 UpdateAPIView。当我完成 View 并运行服务器时,出现以下错误。
Expected view updateViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly.
我想知道为什么我不应该在我的代码中将 lookup_field 指定为 pk 以及我可以使用什么来代替 pk。这是我的代码
序列化器.py
from rest_framework import serializers
from .models import arduino
class arduinoSerializers (serializers.ModelSerializer) :
name = serializers.CharField(source='name.username', read_only=True)
class Meta :
model = arduino
fields = ['name', 'temp', 'humi']
View .py
from .models import arduino
from .serializers import arduinoSerializers
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, UpdateAPIView
class arduinoViewSet (ViewSet) :
serializer_class = arduinoSerializers
def data (self, request) :
queryset = arduino.objects.filter(name=self.request.user)
serializer = arduinoSerializers(queryset, many=True)
return Response(serializer.data)
class createViewSet (CreateAPIView) :
serializer_class = arduinoSerializers
def perform_create (self, serializer) :
serializer.save(name=self.request.user)
def get_queryset (self) :
user = self.request.user
return arduino.objects.filter(name=user)
def dataReceive (self, request) :
queryset = self.get_queryset()
serializer = arduinoSerializers(queryset, many=True)
if serializer.is_valid() :
perform_create(serializer)
return Response(serializer.data)
class updateViewSet (UpdateAPIView) :
serializer_class = arduinoSerializers
lookup_field = 'pk'
def perform_update (self, serializer) :
serializer.update(name=self.request.user)
def get_queryset (self) :
user = self.request.user
return arduino.objects.filter(name=user)
def dataReceive (self, request) :
queryset = self.get_queryset()
serializer = arduinoSerializers(queryset, many=True)
if serializer.is_valid() :
perform_update(serializer)
return Response(serializer.data)
网址.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('api.urls')),
path('auth/', include('rest_auth.urls')),
path('auth/registration/', include('rest_auth.registration.urls')),
]
api\urls.py
urlpatterns = [
path('data/', arduinoViewSet.as_view({'get' : 'data'})),
path('create/', createViewSet.as_view()),
path('update/', updateViewSet.as_view()),
]
提前致谢
最佳答案
更新 View 不知道要更新哪个 id(pk)。尝试在更新网址中添加 pk
urlpatterns = [
path('update/<int:pk>/', updateViewSet.as_view()),
]
关于django - 如何在 Django 中指定 lookup_field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63147070/
我是一名优秀的程序员,十分优秀!