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?
CharField since CharField has a max length of 255 characters while TextField can hold more than 255 characters.
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 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With