alias51
alias51

Reputation: 8618

Why does objects.create() fail silently?

When I create an object via [model].objects.create() and I set one of the field variables incorrectly, the create will fail. However it even with debug=True it does not produce an exception.

E.g. the following fails silently:

Email(models.Model):
   email = models.EmailField()

details = {'email': '1234'} # Fails because it is not a valid EmailField
Email.objects.create(**details)

Why is this, and when I have a large model with lots of fields how can I debug which field is failing?

Upvotes: 1

Views: 1103

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476739

It does not fail silently. Validations do not run when creating, or .save()ing a model object, because of performance reasons. You can raise .full_clean() [Django-doc]. This is specified in the Validating objects section of the documentation:

Note that full_clean() will not be called automatically when you call your model’s save() method. You’ll need to call it manually when you want to run one-step model validation for your own manually created models.

One therefore usually uses a ModelForm [Django-doc] that will perform validation by calling the cleaning functions. These therefore act as a validation layer between the user and the models.

Upvotes: 1

Related Questions