models.fields.Field default value rational

14 views
Skip to first unread message

Rodrigue

unread,
Jun 29, 2009, 5:12:24 PM6/29/09
to Django developers
Hi all,

I came across a behaviour that somewhat surprised me on the model
fields. Namely, if you have a Field with no default value, an empty
value for that field is likely to be turned into the empty string by
Field.get_default.

I came across this behaviour writing unit tests for an applicatioin
I'm working on and where I was expecting my database to complain when
I created and saved an object with no values for one of its
'mandatory' fields. Or at least I expected it to be mandatory.

A quick example:

class DummyModel(models.Model):
mandatory_field = models.CharField(max_length=50)
optional_field = models.CharField(max_length=50, blank=True,
null=True)

empty_object = DummyModel()
empty_object.save()

I would expect this code to raise an IntegrityException -- and I'm
pretty sure it used to be the observed behaviour in older versions.
Instead, I find my database having a DummyModel entry with the empty
string value for mandatory_field and null for optional_field.

Is that not going against the 'madatory-ness' of the field
declaration? I have tried to tell: don't allow empty values for this
field and, obviously, it is not really enforced...

Am I expecting something that is not supposed to be provided by the
Field class but by the form class instead? At any rate, I don't see
why my None should be interpreted as the empty string. So here is my
question: what is the rational behind this behaviour?

cheers,
Rodrigue

Now, the

Tom Evans

unread,
Jun 30, 2009, 4:34:30 AM6/30/09
to django-d...@googlegroups.com

max_length=50 and blank=True are validations that are checked by the
form API/the admin interface. They aren't used to validate at the DB
layer (nothing is).

Re-read http://docs.djangoproject.com/en/dev/ref/models/fields/ , which
also explains the rational to why passing mandatory_field=None to the
constructor results in an empty string being stored for mandatory_field.

Cheers

Tom

Reply all
Reply to author
Forward
0 new messages