Django BooleanField(默认值为False)混乱



这里有人能帮我吗?我正在将数据插入postgreSQL数据库。

admin_created是一个booleanfield,默认情况下设置为false。我已经为第一次训练提供了一个真正的价值,但第二次训练为booleanfield留下了空白。根据我的理解,它应该自动设置为false,但我收到了下面的错误消息。你知道为什么会这样吗?

#.sql
INSERT INTO main_app_workout(name, description, admin_created)
VALUES
('Yoga', 'Roll up your yoga mat and discover the combination of physical and mental exercises that have hooked yoga practitioners around the globe.', 'True');
INSERT INTO main_app_workout(name, description)
VALUES
('Boxing', 'Ready to get your sweat on? Learn the six basic punches to build the foundation of an experienced boxer.');

#models.py
class Workout(Model):
name = models.CharField(max_length=40)
description = models.TextField()
exercises = ManyToManyField(Exercise, blank=True)
admin_created = models.BooleanField(default=False)

#Error code 
psql:db/create_main_exercises.sql:49: ERROR:  23502: null value in column "admin_created" of relation "main_app_workout" violates not-null constraint

编辑:谢谢大家的评论。我对这个问题的解决方案是为种子数据创建的admin_created提供真值。此外,我将admin_created字段更改为

admin_created = models.BooleanField(null=True, default=False)

当我在Django中创建新的模型实例时,它会自动将其设置为False。

Django是为使用ORM而构建的,如果您手动插入,Django无法为您设置默认值,因此将传递NULL。

基于字段的约束只放在django中的代码级别,而不是DB级别。因此,如果您将以编程方式在django中创建一个对象,您就不会面临这个问题。但是当使用SQL创建时,您将面临这个问题。

只有少数约束可用,您可以在DB级别应用,这些约束也发布了django 2.2。

查看django的限制文档此处

最新更新