On Mon, 2009-06-29 at 14:12 -0700, Rodrigue wrote: > 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 >
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 --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Django developers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/django-developers?hl=en -~----------~----~----~----~------~----~------~--~---
