2

Lets say I have a model defined as follows:

class Foo(models.Model):
    bar = models.CharField(max_length=10)

Using this model, I create a Foo object in my database using the following code:

Foo.objects.create(bar="0123456789")

Should work well enough. However, after creating the object, I reduce the max_length property to 5. So now, technically, the object I created has a consistency error.

How does Django manage a situation like this? I assume they don't raise any errors until that object is saved again. If so, is that the optimal solution for a situation like this, and are there are any other approaches?

darkhorse
  • 8,192
  • 21
  • 72
  • 148

2 Answers2

4

Django won't do anything in the situation you describe. However, if you run makemigrations, it will generate a database migration which modifies the db column to 5 characters; running this will truncate the existing values.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
2

It depends on the specific field property. In the case of max_length, it's used in several validation steps in addition to the database itself.

The default html widget will insert a maxlength attribute in the <input> form element. And on the server side, Form.clean() will also check the length of any char fields.

Finally, the database will throw an error (if you have created and applied a new migration after changing the field). But the specific behaviour here depends on the database backend.

Client side validation is just a usability feature. All data coming from the client must also be validated on the server, since client side validation can be bypassed by an attacker, or be turned off or unavailable in some clients.

Django's validation is what you use most of the time. It has error handling and http responses built in if you use a framework/app such as django forms, django admin or django rest framework.

The database validation is fallback when you insert some invalid data even if it's "not supposed to be possible". Errors here could result in a uncaught exception and the entire transaction will be rolled back. It's a very useful safety net when you have bugs in your django application.

Håken Lid
  • 22,318
  • 9
  • 52
  • 67