While subclassing db.models.Model
, sometimes it's essential to add extra checks/constraints.
E.g. I have an Event
model with start_date
and end_date
.
I want to add validation into the fields or the model so that end_date > start_date
.
How many possible ways to do this?
At least I know this can be done outside the models.Model
inside the ModelForm
validation.
But how to attach to the fields and the models.Model
?
To use editable in a field you must specify either of following settings: null=True and blank=True, so that your field doesn't give required error during model save.
To make fields unique together, we create a class Meta. In this class, we specify the keyword, unique_together, and then create a tuple consisting of all the fields that we want unique together. In this case, we just want 2 fields unique together, but you can specify as many as you want, as long as it's 2 or greater.
To create multiple records based on a Django model you can use the built-in bulk_create() method. The advantage of the bulk_create() method is that it creates all entries in a single query, so it's very efficient if you have a list of a dozen or a hundred entries you wish to create.
I would not put constraints like these in the save method, it's too late. Raising an exception there, doesn't help the user who entered the data in the wrong way, because it will end up as a 500 and the user won't get the form with errors back etc.
You should really check for this in the Forms/ModelForms clean method and raise a ValidationError, so form.is_valid()
returns false and you can send the errors in the form back to the user for correction.
Also note that since version 1.2, Django has had Model Validation.
It would look something like this:
class Foo(models.Model): # ... model stuff... def clean(self): if self.start_date > self.end_date: raise ValidationError('Start date is after end date')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With