Django 模型 CharField:max_length 不起作用? [英] django model CharField: max_length does not work?

查看:39
本文介绍了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 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆