我在DRF (Django Rest Framework)中有以下错误:
Internal Server Error: /book/book/
Traceback (most recent call last):
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 70, in view
return self.dispatch(request, *args, **kwargs)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 509, in dispatch
response = self.handle_exception(exc)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 469, in handle_exception
self.raise_uncaught_exception(exc)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
raise exc
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/views.py", line 506, in dispatch
response = handler(request, *args, **kwargs)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/generics.py", line 190, in post
return self.create(request, *args, **kwargs)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/mixins.py", line 20, in create
headers = self.get_success_headers(serializer.data)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 548, in data
ret = super().data
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 246, in data
self._data = self.to_representation(self.instance)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/serializers.py", line 515, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "/home/divyessh/Desktop/Projects/club-booking/booking-new/venv/lib/python3.8/site-packages/rest_framework/fields.py", line 1368, in to_representation
return value.isoformat()
AttributeError: 'SlotChoice' object has no attribute 'isoformat'
以下是我的serializer.py预订:
from rest_framework import serializers
from .models import Booking
from court.serializers import CourtSerializer
from users.models import User
from slots.models import SlotChoice
from datetime import date
class BookingSerializer(serializers.ModelSerializer):
date = serializers.DateField(
required=True,
)
user = serializers.EmailField(required=True)
court = CourtSerializer
slot = serializers.TimeField(required=True)
class Meta:
model = Booking
fields = ('court','user','date', 'slot')
def validate(self, attrs):
d = attrs['date']
now = date.today()
if d <= now:
raise serializers.ValidationError("Date is too old")
s = attrs['slot']
if len(SlotChoice.objects.filter(slot=s)) < 1:
raise serializers.ValidationError("Not an appropriate time slot")
return attrs
def create(self, validated_data):
slot = SlotChoice.objects.filter(slot=validated_data['slot'])[0]
booking= Booking.objects.create(
slot= slot,
date=validated_data['date'],
court=validated_data['court'],
user=User.objects.filter(email=validated_data['user'])[0]
)
booking.save()
return booking
和我的模型是:
slots (models.py)
class SlotChoice(models.Model):
slot = models.TimeField('slot', unique=True)
预订(models.py)
from django.db import models
from users.models import User
from court.models import Court
from slots.models import SlotChoice
class Booking(models.Model):
class Meta:
constraints = [
models.UniqueConstraint(fields=['court', 'date', 'slot'], name="unique_slot")
]
user = models.ForeignKey(User, on_delete=models.CASCADE)
court = models.ForeignKey(Court, on_delete=models.CASCADE)
date = models.DateField('date')
slot = models.ForeignKey(SlotChoice, on_delete = models.CASCADE)
我在SO上尝试了一些解决方案,但无法解决此错误。请帮助我解决这个错误。如有任何帮助,不胜感激。
在序列化器内部:
class BookingSerializer(serializers.ModelSerializer):
...
slot = serializers.TimeField(required=True)
...
slot
是TimeField
但Booking
模型将slot
作为SlotChoice
对象。
class Booking(models.Model):
...
slot = models.ForeignKey(SlotChoice, on_delete = models.CASCADE)
...
因此Booking
返回SlotChoice
对象,BookingSerializer
试图将slot
解释为类似time
的对象。
您需要添加SlotChoiceSerializer
并更改BookingSerializer
,如
class BookingSerializer(serializers.ModelSerializer):
...
slot = SlotChoiceSerializer()
# or something like ↓ (I'm not familiar with this stuff, so check links below to get details)
# slot = serializers.StringRelatedField(many=False)
...
# where SlotChoiceSerializer is
class SlotChoiceSerializer(serializers.ModelSerializer):
...
slot = serializers.TimeField(required=True)
...
class Meta:
model = SlotChoice
...
之后可以通过BookingSerializer.slot.slot
访问TimeField
的值
这里是关于ForeignKey
和嵌套序列化器的几个链接:
Django Rest框架嵌套序列化器
https://www.django-rest-framework.org/api-guide/relations/