Italo Lemos
Italo Lemos

Reputation: 1022

Set a value in Model field based on another value from other model

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,...)

Upvotes: 1

Views: 458

Answers (1)

weAreStarsDust
weAreStarsDust

Reputation: 2752

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)

Upvotes: 1

Related Questions