【问题标题】:Django Integrity Error "Column 'section_id' cannot be null" [duplicate]Django 完整性错误“列'section_id'不能为空”[重复]
【发布时间】:2018-03-16 14:45:40
【问题描述】:

我在 Django 中看到了很多关于这个错误的问题,但我很茫然,因为据我所知,我的数据库中没有一个表有 section_id 列。当用户尝试注册并且 views.py 尝试创建用户时,我收到错误消息。我最近在我的应用程序中更改了“配置文件”模型(Profile 对象与 User 对象一起自动创建)以具有 section 属性而不是section_id 属性,但我重置了迁移并重新创建了几次数据库。我认为这可能是进行迁移的问题,但我真的不知道。

这是曾经具有 section_id 属性的配置文件模型:

class Profile(models.Model):
    """
    An extension of the built-in Django user model to allow for the different types of users
    """
    USER_TYPES = (
        ('S', 'Student'),
        ('I', 'Instructor'),
        ('C', 'Client')
    )
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_type = models.CharField(max_length=1, choices=USER_TYPES)
    section = models.ForeignKey(Section, default=None)

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

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    if instance.is_staff != 1:
        instance.profile.save()

这是引发错误的代码:

new_user = User.objects.create_user(email, email=email, password=password)

【问题讨论】:

  • "我的数据库中没有一个表有section_id 列",实际上是指Profile 模型中的section 列。你为什么不试试section = models.ForeignKey(Section, blank=True, null=True)
  • 并为user_type设置默认值
  • 你是救生员@AvinashRaj!

标签: python mysql django


【解决方案1】:

就像 Avinash Raj 所说,为 section 属性设置空白和 null 就可以了:

section = models.ForeignKey(Section, blank=True, null=True)

【讨论】:

    猜你喜欢
    • 2014-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多