I have two models where one has a ForeignKey relationship with other entity. The thing is the date in data_start
field from ModelB needs to be not equal and grater than the date in date_end
from ModelA. How can I do this comparison(rule) inside the ModelB and save it?
class ModelB(models.Model):
date_start = models.DateTimeField('')
date_end = models.DateTimeField('')
class ModelA(models.Model):
name = models.CharField(...)
date_start = models.DateTimeField('')
date_end = models.DateTimeField('')
resource = models.ForeignKey(ModelB,...)
I think it is more correct to check this condition from ModelA
, because in your structure there can be several ModelA
instances for one ModelB
instance, and it is not clear with which variant of ModelA
compare date in this case.
So override save() method of ModelA
and check condition there
class ModelA(models.Model):
name = models.CharField(...)
date_start = models.DateTimeField('')
date_end = models.DateTimeField('')
resource = models.ForeignKey(ModelB,...)
def save(self, *args, **kwargs):
if self.date_end <= self.resource.date_start:
raise Exception("resource.date_start can't be equal or grater then date_end")
super().save(*args, **kwargs)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.