gpt4 book ai didi

django - 如何在 Django 中指定 lookup_field

转载 作者:行者123 更新时间:2023-12-05 07:03:46 27 4
gpt4 key购买 nike

我将在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com