SQLite Doesn't Care About Your max_length

Posted by Chris Bartos on July 25, 2016

SQLite databases don’t care about your using of max_length on your models. Let’s look at an example.

models.py

class Book(models.Model):
    title = models.CharField(max_length=30)

Now, we’ll run some queries.

$ ./manage.py makemigrations
$ ./manage.py migrate
$ ./manage.py shell
>>> from book.models import Book
>>> title = 'A' * 31
>>> print len(title)
31
>>> book = Book.objects.create(title=title)
>>> book.save()
>>> len(book.title)
31

When running SQL queries using SQLite, you find that you can create records and the database will save a CharField with attributes with bigger strings than what the max_length describes.

Is there any way we can fix this? Sure there is!

One way that we can validate if our model instance is correct is to run a method called full_clean().

So, what we can do is override our save() method so that we can validate our SQLite model before we save our model. Let’s take a look.

class Book(models.Model):
    title = models.CharField(max_length=10)

    def save(self, *args, **kwargs):
        try:
            self.full_clean()
            super(Book, self).save(*args, **kwargs)
        except:
            print "Error saving model"

As you can see, if self.full_clean() throws an error, our instance will print out ‘Error saving model’ and our save method will not save our record to the database.

Try this out next time you use SQLite for your database.

I hope that works for you!

Chris

Django REST Framework Email Course

You'll get 1 lesson everyday for 7 days. You'll learn:
  • Serializers
  • Request Methods
  • Endpoints
  • Basic Authentication
  • and more...
Powered by ConvertKit

Would you rather do laundry and binge on Netflix shows than attempt to learn Django REST Framework?

You can learn Django REST Framework in ONE week at about 15 - 30 minutes per day (1 lesson per day for the next 7 days).

Click the button below to sign up and start learning Django REST Framework today!

click here to receive the first lesson in minutes!
(once you sign up, you'll get a new lesson everyday for the next 7 days)