Django OneToOneField默认值

时间:2018-03-25 17:22:59

标签: python django

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

django.db.utils.IntegrityError: NOT NULL constraint failed: 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)

2 个答案:

答案 0 :(得分:5)

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

要么null=True

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

或使用信号将用户与相册相关联。

答案 1 :(得分:1)

因为:

1)相册中的所有字段都可以为空或具有默认值,并且

2)您可以将可调用对象传递给默认arg

这应该有效:

album = models.OneToOneField(Album, on_delete=models.CASCADE, default=Album.objects.create)