anshul
anshul

Reputation: 23

How Do i compare Two model fields against each other in django?

I have this Model in my Models.py file.I want to to compare "start_date" and "end_date" so that start_date value would never be greater then end_date or vice-versa.How do i do this validation?

class Completion(models.Model):

    start_date = models.DateField()
    end_date = models.DateField()
    batch = models.ForeignKey(Batch)
    topic = models.ForeignKey(Topic)

Upvotes: 2

Views: 2703

Answers (1)

I'd start getting your head into the Model Validation framework. http:https://docs.djangoproject.com/en/2.0/ref/models/instances/#django.db.models.Model.clean

It's used by ModelForms and just makes a whole lot of sense to start using it.

Basically, you'd define a clean() method in your model, put in your validation logic, and raise ValidationError if it fails.

class MyModel(models.Model):
    def clean(self):
        from django.core.exceptions import ValidationError
        if self.start_data > self.end_date:
            raise ValidationError('Start date cannot precede end date')


    def save(self, *args, **kwargs):
        # you can have regular model instance saves use this as well
        super(MyModel, self).save(*args, **kwargs)

The benefit here is that any ModelForm (which means the admin site too will call full_clean(), which in turn calls your model clean() without any extra work.

No need to override save_model, you'll get the usual validation errors at the top of the admin form. description

Finally, it's super convenient. You can use it anywhere.

try:
    my_model.full_clean()
except ValidationError, e:
    # Do something based on the errors contained in e.message_dict.
    # Display them to a user, or handle them programatically.

Upvotes: 10

Related Questions