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?

2
  • blank=True / False is allowed at the model level. See 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, 2014 at 1: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, 2014 at 1:40

1 Answer 1

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()?

2
  • 1
    Also see this answer by a Django committer: stackoverflow.com/a/1625760/262819
    – cjerdonek
    Jan 28, 2014 at 1: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, 2014 at 2:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.