Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 466
Xun Yang Avatar asked Dec 12 '11 17:12

Xun Yang


People also ask

What is the max length of CharField in Django?

CharField since CharField has a max length of 255 characters while TextField can hold more than 255 characters.

What is Max_length in Django?

The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django's validation using MaxLengthValidator . If you are writing an application that must be portable to multiple database backends, you should be aware that there are restrictions on max_length for some backends.

How do you use CharField?

How to use CharField ? CharField is used for storing small sized strings in the database. One can store First Name, Last Name, Address Details, etc. CharField should be given an argument max_length for specifying the maximum length of string it is required to store.

What is a CharField?

CharField is a commonly-defined field used as an attribute to reference a text-based database column when defining Model classes with the Django ORM. The Django project has wonderful documentation for CharField and all of the other column fields.


1 Answers

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.
like image 98
Alasdair Avatar answered Sep 20 '22 01:09

Alasdair