gpt4 book ai didi

django 模型 CharField : max_length does not work?

转载 作者:IT王子 更新时间:2023-10-29 06:19:31 25 4
gpt4 key购买 nike

我正在尝试创建一个选择有限的字段:

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 作为后端。

应该是这样的吗?或者如果我错过了什么?

最佳答案

SQLite 不强制 VARCHAR 的长度。

来自SQLite Frequently asked questions :

(9) What is the maximum size of a VARCHAR in SQLite?

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 管理或模型表单更新数据库,Django 将为您进行长度验证。在 shell 中,您可以手动调用 full_clean在保存之前,捕获验证错误。

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 does not work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8478054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com