django 手动将模型字段添加到 postgres 数据库

Posted

技术标签:

【中文标题】django 手动将模型字段添加到 postgres 数据库【英文标题】:django add model field manualy to postgres database 【发布时间】:2014-01-01 15:41:35 【问题描述】:

我不能使用 south,也没有 pgAdmin,但我需要在模型末尾添加新字段。我需要:

new_field = models.CharField(max_length=200, blank=True, null=True)

我有 ssh 访问权限并定义了 psql 用户,所以我需要语法来将该字段添加到模型数据库表中。 ALTER TABLE store_products ADD COLUMN description text; 能完成这项工作吗?如何将 max_length 200、空白和 null 设置为 true? postgresql 9.1,django 1.6。

【问题讨论】:

为什么不用南方呢? south.readthedocs.org/en/latest 【参考方案1】:

我认为blank=Truenull=True 表示应该允许空字符串和NULL 值。这些是默认值,您无需执行任何额外操作。

对于max_length=200,您可以使用varchar(200) 而不是text

ALTER TABLE store_products ADD COLUMN description varchar(200);

但我通常更喜欢将数据类型 textCHECK constraint 结合使用:

ALTER TABLE store_products ADD COLUMN description text;
ALTER TABLE store_products ADD CONSTRAINT description_max200
CHECK (length(description) <= 200);

【讨论】:

以上是关于django 手动将模型字段添加到 postgres 数据库的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Python 迁移将 Heroku Django 应用程序的新模型表添加到远程 Heroku Postgres?

将用户友好的 json 编辑器添加到 django admin

将用户友好的json编辑器添加到django admin

如何将字段添加到现有模型[重复]

手动将 js 文件添加到另一个 js 文件之间的页面(订单计数)

如何将组装字段添加到 Pydantic 模型