django model CharField: max_length does not work?(Django 模型 CharField:max_length 不起作用?)
问题描述
我正在尝试创建一个选择有限的字段:
I'm trying to make a field with limited choices:
Action_Types=(
('0','foo'),
('1','bar'),
)
class Foo(models.Model):
myAction=models.CharField(max_length=1,choices=Action_Types)
def __unicode__(self):
return '%d %s'%(self.pk,self.myAction)
但是,当我尝试插入违反规则的内容时,它成功了,没有任何错误或警告消息(使用manage.py shell").似乎任何长度的任何文本都可以放入此字段.我使用 SQLite3 作为后端.
However, when I was trying to insert content violating the rules, it succeeded without any error or warning messages (with "manage.py shell"). It seems any text of any length can be put into this field. I'm using SQLite3 as the backend.
应该是这样吗?或者如果我错过了什么?
Is it supposed to be like that? Or if I missed something?
推荐答案
SQLite 不强制 VARCHAR 的长度.
SQLite does not enforce the length of a VARCHAR.
来自SQLite 常见问题:
(9) SQLite 中 VARCHAR 的最大大小是多少?
SQLite 不强制 VARCHAR 的长度.您可以声明一个 VARCHAR(10) 并且 SQLite 很乐意让您在其中放置 500 个字符.它将保持所有 500 个字符完整 - 它永远不会被截断.
SQLite does not enforce the length of a VARCHAR. You can declare a VARCHAR(10) and SQLite will be happy to let you put 500 characters in it. And it will keep all 500 characters intact - it never truncates.
如果您使用 django admin 或模型表单更新数据库,Django 将为您进行长度验证.在 shell 中,您可以手动调用 full_clean
保存之前,并捕获验证错误.
If you update the database using the django admin or model forms, Django will do the length validation for you. In the shell, you could manually call full_clean
before saving, and catch the validation error.
f = Foo(myAction="more than 1 char")
try:
f.full_clean()
f.save()
except ValidationError as e:
# Do something based on the errors contained in e.message_dict.
这篇关于Django 模型 CharField:max_length 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Django 模型 CharField:max_length 不起作用?


- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- SQL 临时表问题 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01