gpt4 book ai didi

python - Django OneToOneField 默认值

转载 作者:太空狗 更新时间:2023-10-29 21:45:06 24 4
gpt4 key购买 nike

最近我在 django 模型中添加了一个 OneToOneField ,我在该字段中将 None 设置为默认值。然后我得到了这个错误:

django.db.utils.IntegrityError:NOT NULL 约束失败:user_myuser.album_id

型号:

class MyUser(models.Model):

username = models.CharField(unique=True, max_length=25)
first_name = models.CharField(max_length=50, default='')
last_name = models.CharField(max_length=70, default='')
register_date = models.DateTimeField(default=timezone.now)
update_at = models.DateTimeField(auto_now=True)

# the default value problem is here
album = models.OneToOneField(Album, auto_created=True,
on_delete=models.CASCADE, default=None)

这是专辑模型:

class Album(models.Model):
name = models.CharField(max_length=100, null=True)
author = models.CharField(max_length=100, null=True)
picture_address = models.ImageField(upload_to=album_upload_destination, null=True)
creation_year = models.IntegerField(default=-1)
rate = models.IntegerField(default=0)
timestamp = models.DateTimeField(auto_now_add=True)

最佳答案

由于 NOT NULL 约束失败,因此出现错误。

要么使null=True

album = models.OneToOneField(Album,on_delete=models.CASCADE, null=True)

或者使用信号将用户与相册联系起来。

关于python - Django OneToOneField 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49478700/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com