【发布时间】:2021-09-18 11:05:30
【问题描述】:
有人可以帮我吗?我正在将数据插入到我的 postgreSQL 数据库中。
admin_created 是一个布尔字段,默认设置为 false。我为第一次锻炼提供了真实值,但将第二次锻炼留为布尔字段空白。根据我的理解,它应该自动设置为 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
编辑: 谢谢大家的cmets。我对这个问题的解决方案是为种子数据的 admin_created 提供真实值。此外,我将 admin_created 字段更改为
admin_created = models.BooleanField(null=True, default=False)
当我在 Django 中创建模型的新实例时,它会自动将其设置为 False。
【问题讨论】:
-
Workout模型是否由 django 管理?据我所知,default是用于 django 管理模型本身的时候,它不会反映在数据库级别的列中。所以这里的默认值只有在你使用 ORM 时才会生效
标签: django postgresql django-models