【问题标题】:django IntegrityError for create object [duplicate]创建对象的django IntegrityError [重复]
【发布时间】:2021-08-15 05:35:54
【问题描述】:

我有这个模型。当我对 Profile 模型中的 real_estate 字段使用一对一关系并创建新对象时,我收到此错误 =>

/admin/users/profile/add/ 处的 IntegrityError

NOT NULL 约束失败:users_profile.real_estate_id


class Business(models.Model):
    name = models.CharField(max_length=200)
    image = models.ImageField()
    homes = models.ManyToManyField(Homes , related_name='home', blank=True)
    create = models.DateField(auto_now_add=True)
    number = models.IntegerField()

class Profile(models.Model):
    CHOICES = (
        ('RE', 'مشاور املاک'),
        ('S', 'فروشنده'),
    )

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    real_estate = models.OneToOneField(Business , related_name='business' ,on_delete=models.CASCADE, blank=True)
    image = models.ImageField(blank=True)
    type_of_user = models.CharField(max_length=300, choices=CHOICES)
    phone_number = PhoneNumberField(unique = True, null = False, blank = False)

【问题讨论】:

    标签: python-3.x django django-models


    【解决方案1】:

    您应该在问题中添加完整代码。所以不能假设你是如何尝试的。

    如果要允许null,可以这样试试:

    real_estate = models.OneToOneField(Business , related_name='business' ,on_delete=models.SETNULL, blank=True, null=True)
    

    并重新迁移,它不应该再次触发您同样的错误

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 2021-02-02
      • 2019-12-09
      • 1970-01-01
      • 2018-02-19
      • 2012-09-16
      相关资源
      最近更新 更多