(1048,“列 'user_id' 不能为空”)与 Django DRF

Posted

技术标签:

【中文标题】(1048,“列 \'user_id\' 不能为空”)与 Django DRF【英文标题】:(1048, "Column 'user_id' cannot be null") with Django DRF(1048,“列 'user_id' 不能为空”)与 Django DRF 【发布时间】:2021-09-03 03:18:03 【问题描述】:

我编写了代码以通过 POST 和 DRF(Django Rest Framework)成功创建新用户,并且我可以正确获取令牌,但是当我尝试 POST(通过 DRF)来填写链接到该用户的个人资料时,我得到了 (1048, "列 'user_id' 不能为空")

This is snippets of my code:
for serializers:
class UserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = ('username','email','first_name','last_name','password')
    def create(self, *args, **kwargs):
        user = super().create(*args, **kwargs)
        p = user.password
        user.set_password(p)
        user.save()
        return user

    def update(self, *args, **kwargs):
        user = super().update(*args, **kwargs)
        p = user.password
        user.set_password(p)

        user.save()
        return user

class ProfileSerializer(ModelSerializer):
    class Meta:
        model = Profile
       
        fields = ('bio','birth_date','location','country')

    def create(self, *args, **kwargs):
        profile = super().create(*args, **kwargs)
        profile.save()
        return profile
    
    def update(self, *args, **kwargs):
        profile = super().update(*args, **kwargs)
        profile.save()
        return profile

and for views:
class ProfileViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    permission_classes = IsAuthenticated,
    serializer_class = ProfileSerializer
    queryset = Profile.objects.all()


class UserViewSet(viewsets.GenericViewSet,mixins.CreateModelMixin,):
    """
    API endpoint that allows users to be viewed or edited.
    """
    #permission_classes= (IsAdminUser,)
    serializer_class = UserSerializer
    queryset = User.objects.all().order_by('-date_joined')

and for models:
@receiver(post_save, sender = settings.AUTH_USER_MODEL)
def create_auth_token(sender,instance=None,created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)


class Country(models.Model):
    iso = models.CharField(max_length = 2,unique = True)
    name = models.CharField(max_length = 250)
    iso3 = models.CharField(max_length = 6)
    phonecode = models.CharField(max_length=6)
    def __unicode__(self):
        return '%s' % self.name
    def __str__(self):
        return '%s' % self.name

class Profile(models.Model):
    #user = models.OneToOneField(User, on_delete=models.CASCADE,default = "")
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default = "")
    bio = models.TextField(max_length=100, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    location = models.CharField(max_length=254, blank=True)
    country = models.ForeignKey(Country,on_delete=models.CASCADE,blank=True,null=True)
    def __unicode__(self):
        return '%s' % self.user
    def __str__(self):
        return '%s' % self.user

@receiver(post_save, sender=User)
def update_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

当我尝试使用 Postman 并传递令牌进行令牌身份验证时,它可以正确识别令牌,但出现以下错误: (1048,“列 'user_id' 不能为空”)与 Django DRF 感谢您帮助解决此问题

【问题讨论】:

【参考方案1】:

Create() 保存到数据库,所以调用函数前需要设置profile.user_id。

【讨论】:

感谢您的回答,我不明白您的意思是保存到数据库中,代码中已经有 profile.save() ,我将从哪里获取 user_id 值?可以举个例子吗? Create() 在里面调用这个 .save() 所以你的 profile.save() 是多余的,这是你的代码,你将用户字段设置为一个外键 null 也不允许所以你告诉我您应该从哪里获取信息可能来自 request.user 这将回答你的问题***.com/questions/30203652/… 对于嵌套序列化程序,您必须编写自己的 create() 和 update() 方法。如果还有问题,请告诉我。

以上是关于(1048,“列 'user_id' 不能为空”)与 Django DRF的主要内容,如果未能解决你的问题,请参考以下文章

p1048洛谷P1048采药题解

1048 - Conquering Keokradong

1048. Find Coins (25)

SQLSTATE [23000]:完整性约束违规:1048 laravel 5.7

PAT1048:Find Coins

1048 石子归并