1

In Django, I would like the ability to mark certain model fields as required at the model (or at least database) level, to make sure that I am specifying them explicitly (i.e. not relying on defaults) when creating objects.

Currently, Django lets you designate a model field as required at the forms level (by specifying blank=False in the model). However, it doesn't seem like there is a similar option to get this behavior at the model or database level.

It does seem like there are various hacks to achieve something similar though. For example, you can set the default to something that violates a database constraint. For example, you can do things like:

models.CharField(_('characters'), max_length=4, default=None)

or

models.CharField(_('characters'), max_length=4, default="abcdef")

The former example works when saving to the database since None violates the default not-null constraint of null=False (raising an IntegrityError). The latter works because a DataError is raised when saving. But I don't know if this is guaranteed to work across all databases, etc.

Am I missing something, or is there a better way?

cjerdonek
  • 5,814
  • 2
  • 32
  • 26
  • blank=True / False *is* allowed at the model level. See https://docs.djangoproject.com/en/dev/ref/models/fields/#blank For CharField it's not a database constraint, just a forms validation constraint. I think if you do a model.full_clean() and then model.save() the blank=False check would execute. – Nils Jan 28 '14 at 01:27
  • @CantucciHQ, I understand all that. By "required at the model level," I mean that I want the enforcement/validation to occur at the model level, even if the forms API is not used. – cjerdonek Jan 28 '14 at 01:40

1 Answers1

0

If django models called full_clean() automatically on save(), your check would run at the model level without a form. I've been playing with making this the default behavior in my django projects by creating an auto-clean model subclass which does full_clean() on save(), then deriving my models off that.

If you want to learn why it isn't already like this: Why doesn't django's model.save() call full_clean()?

Community
  • 1
  • 1
Nils
  • 5,612
  • 4
  • 34
  • 37
  • 1
    Also see this answer by a Django committer: http://stackoverflow.com/a/1625760/262819 – cjerdonek Jan 28 '14 at 01:55
  • I hadn't seen that explanation before, it's a better link than the one I gave. Thanks! Basically, any validation short of DB validation isn't air-tight. – Nils Jan 28 '14 at 02:00