Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
787 views
in Technique[技术] by (71.8m points)

sqlite - django model CharField: max_length does not work?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...