django Rest-frame-work user_id 相关“违反非空约束”

问题描述 投票:0回答:1

我有这个错误

jango.db.utils.IntegrityError: null value in column "user_id" of relation "defapp_actionlog" violates not-null constraint
DETAIL:  Failing row contains (13, "{\"action\":\"push\"}", 2024-10-21 06:11:30.43758+00, 2024-10-21 06:11:30.43759+00, null).

我想要做的是从 javascript 推送操作日志并将登录用户设置为模型。

我将

CustomUser
对象设置为
user
行,但它仍然需要
user_id

我的视图集、模型、序列化器如下所示。

class ActionLogViewSet(viewsets.ModelViewSet):
    queryset = m.ActionLog.objects.all()
    serializer_class = s.ActionLogSerializer
    
    def perform_create(self, serializer):
        obj = serializer.save()
        return obj

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)   
        request.data._mutable = True
        request.data['user'] = m.CustomUser.objects.get(id=request.user.id)
        try:
            serializer.is_valid(raise_exception=True)
        except Exception as e:
            logger.info(e)

        self.perform_create(serializer)
        return Response(serializer.data)



class ActionLog(models.Model):
    user = models.ForeignKey(CustomUser,on_delete=models.CASCADE,related_name='action_user')
    detail = models.JSONField(default=dict,null=True, blank=True) 
    created_at = models.DateTimeField(auto_now_add=True)    
    updated_at = models.DateTimeField(auto_now=True) 
    
class ActionLogSerializer(ModelSerializer):
    id = serializers.IntegerField(read_only=True)
    user = CustomUserSerializer(read_only=True,source="actionlog_user")
    detail = serializers.CharField()
    class Meta:
        model = m.ActionLog
        fields = ('id','user','detail')
django django-rest-framework model
1个回答
0
投票

正如我所见,您在这里使用 ModalSerilizer,因此您不需要在序列化器中显式添加 id 字段。在使用 ModalSerilizer 类时,只有您想要自定义的字段应该出现在序列化器字段中

© www.soinside.com 2019 - 2024. All rights reserved.