How Do i compare Two model fields against each other in django? -
i have model in models.py file.i want to compare "start_date" , "end_date" start_date value never greater end_date or vice-versa.how do validation?
class completion(models.model): start_date = models.datefield() end_date = models.datefield() batch = models.foreignkey(batch) topic = models.foreignkey(topic)
i'd start getting head model validation framework. http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.model.clean
it's used modelforms
, makes whole lot of sense start using it.
basically, you'd define clean()
method in model, put in validation logic, , raise validationerror
if fails.
class mymodel(models.model): def clean(self): 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): # can have regular model instance saves use super(mymodel, self).save(*args, **kwargs)
the benefit here modelform
(which means admin site too call full_clean()
, in turn calls model clean()
without work.
no need override save_model
, you'll usual validation errors @ top of admin form.
finally, it's super convenient. can use anywhere.
try: my_model.full_clean() except validationerror, e: # based on errors contained in e.message_dict. # display them user, or handle them programatically.
Comments
Post a Comment