我有EndPoint,可让用户预订大厅。但是,当我尝试预订大厅时,会出现错误 NOT NULL constraint failed
。我锁定问题'NOT NULL constraint failed' after adding to models.py。他们建议在字段中添加null。但就我而言,我必须保存大厅ID,否则我不知道用户正在预订的大厅(它在大厅中保存为空)
在开始时显示此错误:NOT NULL constraint failed: api_bookingmodel.user_id
,我通过添加函数perform_create ... serializer.save(user=self.request.user)
这是我的代码。...
模型类
class HallModel(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='hall_owner')
name = models.CharField(max_length=100)
price = models.FloatField()
phone = models.CharField(max_length=9, blank=True)
size = models.CharField(max_length=50)
region = models.CharField(max_length=100)
state = models.CharField(max_length=100)
image_1 = models.ImageField(upload_to='halls_image')
image_2 = models.ImageField(upload_to='halls_image')
image_3 = models.ImageField(upload_to='halls_image')
created_at = models.DateTimeField(auto_now_add=True)
class BookingModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_booking')
hall = models.ForeignKey(HallModel, on_delete=models.CASCADE, related_name='hall_owner')
time_date = models.DateTimeField(auto_now_add=True)
booking_method = models.IntegerField()
序列化器
class HallSerializer(serializers.ModelSerializer):
booking = serializers.SerializerMethodField()
class Meta:
model = HallModel
fields = '__all__'
def get_booking(self, obj):
booking = BookingSerializer(obj.hall_owner.all(),many=True).data
return booking
def perform_create(self, serializer):
serializer.save()
class BookingSerializer(serializers.ModelSerializer):
hall = serializers.SerializerMethodField()
class Meta:
model = BookingModel
fields = '__all__'
depth = 1
def get_hall(self, obj):
serializer_data = HallSerializer(obj.hall).data
return serializer_data
视图集
class HallViewSet(viewsets.ModelViewSet):
queryset = HallModel.objects.all()
serializer_class = HallSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class BookingViewSet(viewsets.ModelViewSet):
serializer_class = BookingSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get_queryset(self):
return self.request.user.user_booking.all()
它显示此错误:IntegrityError at /api/booking/
NOT NULL constraint failed: api_bookingmodel.hall_id
...我想我必须将Hall ID保存在perform_create函数中,但我无法执行。 最奇怪的是,当我在预订序列化程序中删除depth = 1
时,并没有显示错误提示 ...任何人都有解决方法。
答案 0 :(得分:0)
您可以在BookingViewSet类中覆盖 TOOLCHAIN_TARGET_TASK_append = " <package>-staticdev <package>-dev"
,如下所示:
def perform_create
确保在发布请求中准备好hall_id。 HallSerializer中的def perform_create(self, serializer):
serializer.save(
user=self.request.user,
hall=self.request.data['hall_id']
)
也没有用。阅读cdrf.co