You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中BedroomSummary的user_id非空约束报错,无法关联用户uuid求助

解决Django DRF中BedroomSummary创建时user_id非空约束报错

错误信息

关系core_bedroomsummary的user_id列存在空值,违反非空约束 | 详情:失败行包含(2, title, string, null)。

问题根源

BedroomSummary模型里user是必填外键,但创建评论时未自动关联当前已认证用户:

  • 序列化器未包含user字段,且存在拼写错误(read_only_field应为复数read_only_fields)
  • 视图集未在创建实例时将当前用户赋值给user字段,导致写入数据库时user_id为空,触发非空约束。

解决方案

1. 修正序列化器(serializers.py)

添加user字段到返回字段并设为只读,同时修正拼写错误:

class BedroomSummarySerializer(serializers.ModelSerializer):
    """Serializer for interior summary."""

    class Meta:
        model = BedroomSummary
        fields = ['id', 'title', 'comment', 'user']
        read_only_fields = ['id', 'user']  # 修正复数拼写,将user设为只读

2. 重写视图集的perform_create方法(views.py)

在创建评论时自动关联当前已认证用户:

class BedroomSummaryViewSet(mixins.DestroyModelMixin,
                            mixins.UpdateModelMixin,
                            mixins.ListModelMixin,
                            mixins.CreateModelMixin,
                            viewsets.GenericViewSet):
    """Manage comments in the database."""
    serializer_class = serializers.BedroomSummarySerializer
    queryset = BedroomSummary.objects.all()
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        """Filter queryset to authenticated user."""
        return self.queryset.filter(user=self.request.user).order_by('-title')
    
    def perform_create(self, serializer):
        """自动关联当前用户到新创建的评论"""
        serializer.save(user=self.request.user)

原模型代码参考

models.py

class BedroomSummary(models.Model):
    """Bedroom Summary Model"""
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    title = models.CharField(max_length=55)
    comment = models.CharField(max_length=2000)

内容的提问来源于stack exchange,提问作者im_up

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 19:20:20