我正在尝试RetrieveUpdateDeleteAPIView和my更新方法,每次更新课程对象时都会给出一个关键错误
更新方法工作
api_views.py
from rest_framework.generics import (
RetrieveUpdateDestroyAPIView
)
from .serializers import CourseSerializer
from .models import Course
from django.core import cache
class CourseRetrieveUpdateDestroy(RetrieveUpdateDestroyAPIView):
queryset = Course.objects.all()
lookup_field = 'id'
serializer_class = CourseSerializer
def delete(self, request, *args, **kwargs):
course_id = request.data.get('id')
response = super().delete(request, *args, **kwargs)
if response.status_code == 204:
cache.delete('course_data_{}'.format(course_id))
return response
def update(self, request, *args, **kwargs):
response = super().update(request, *args, **kwargs)
if response.status_code == 200:
from django.core.cache import cache
course = response.data
cache.set('course_data_{}'.format(course['id']), {
'title' : course['title'],
'description': course['description'],
'featured': course['featured'],
})
return responseserializers.py
from rest_framework import serializers
from .models import Course
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = ('title', 'description', 'issued_at', )
def to_representation(self, instance):
data = super().to_representation(instance)
data['time_passed'] = instance.time_passed()
data['is_fresh'] = instance.is_fresh
return dataurls.py
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
from .views import (
CourseListView,
CourseDetailView
)
from .api_views import (
#CourseList,
#CourseCreate,
CourseRetrieveUpdateDestroy
)
app_name = 'courses'
urlpatterns = [
path('', CourseListView.as_view(), name="course_list"),
path('course/<int:pk>/', CourseDetailView.as_view(), name="course_detail"),
#api-views
path('api/course/<int:id>/', CourseRetrieveUpdateDestroy.as_view(), name="course_rud_api"),
#path('api/list/', CourseList.as_view(), name="course_list_api"),
#path('api/create/', CourseCreate.as_view(), name="course_create_api"),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)**每当我试图更新给定id的对象并点击enter时,都会返回一个KeyError at /course/api/course/2/(以id=2为例) 'id‘作为键。
为什么它给了我一个关键错误的字段,我还没有要求序列化在serializers.py?即使在将我重定向到错误页面之后,模型也会更新。如何解决此错误或避免此错误页?
发布于 2021-05-17 17:05:07
您没有将id字段包含在序列化程序fields中,因此它不会出现在响应数据中。试试这个:
class CourseSerializer(serializers.ModelSerializer):
class Meta:
model = Course
fields = ('id', 'title', 'description', 'issued_at', )默认情况下,id将是只读字段.因此,用户在发送数据时不能覆盖它,但是它将在发送的响应数据中。
https://stackoverflow.com/questions/67572534
复制相似问题