django model CharField: max_length does not work?

本秂侑毒 提交于 2020-01-09 11:06:07

问题


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)

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?


回答1:


SQLite does not enforce the length of a VARCHAR.

From the 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.

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.


来源:https://stackoverflow.com/questions/8478054/django-model-charfield-max-length-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!