简体   繁体   English

IntegrityError:NOT NULL 约束失败:

[英]IntegrityError: NOT NULL constraint failed:

from django.db import models
from django.contrib.auth.models import User


class TaskList(models.Model):
    manage = models.ForeignKey(User, on_delete=models.CASCADE, default=None)
    task = models.CharField(max_length=300)
    done = models.BooleanField(default=False)

    def __str__(self):
        return self.task + " - " + str(self.done)

I keep getting this error: NOT NULL constraint failed: new__todolist_app_tasklist.manage_id after I "python manage.py migrate".我不断收到此错误:NOT NULL constraint failed: new__todolist_app_tasklist.manage_id 在我“python manage.py migrate”之后。

Any suggestions?有什么建议么?

Try to set the ForeignKey to null=True to allow None values, as this is the default you defined.尝试将ForeignKey设置为null=True以允许None值,因为这是您定义的默认值。

from django.db import models
from django.contrib.auth.models import User


class TaskList(models.Model):
    manage = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default=None)
    task = models.CharField(max_length=300)
    done = models.BooleanField(default=False)
    # ...

As you are setting on_delete=models.CASCADE , all TaskList of a user will be deleted, if you delete the related User object.当您设置on_delete=models.CASCADE时,如果您删除相关的User对象,则将删除用户的所有TaskList If this is the desired behaviour, null=True, default=None should not be necessary and used.如果这是所需的行为, null=True, default=None不应该是必要的和使用。

If you like to keep the TaskList even if the User ist deleted, use on_delete=models.SET_NULL , as yopu already having TaskList objects with None values for the manage field.如果您想保留TaskList即使User被删除,请使用on_delete=models.SET_NULL ,因为 yopu 已经有TaskList对象的manage字段值为None

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM