Django 模型 CharField:max_length 不起作用?

2022-01-02 00:00:00 django model sqlite maxlength choice

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

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.

相关文章