I have two models
class JobPosition(models.Model):
...
position_status = models.CharField(choices=POSITION_STATUS)
class Outreach(models.Model):
...
outreach_status = models.CharField(choices=OUTREACH_STATUS, max_length=20)
position = models.ForeignKey('action.JobPosition', on_delete=models.CASCADE, related_name='feelers')
I want the position_status of jobposition to be, at any time, the highest of the outreach_status of the outreaches that are related to it (feelers). Where "highest" is set by an arbitrary rule of mine that we can ignore.
My thinking is to override the save method of the outreach model and make it so that when the status of the outreach changes, I trigger an update status in the jobposition model to update the status of the position.
However, I am realizing that within the safe method, the status of the outreach is still not updated in the DB so if I trigger something on the jobposition model, it would not work.
Any other idea? I can do everything in the outreach method but it would have to be an ugle function and I was hoping there was a better way within the jobposition model.
CodePudding user response:
class Outreach(models.Model):
...
outreach_status = models.CharField(choices=OUTREACH_STATUS, max_length=20)
position = models.ForeignKey('action.JobPosition', on_delete=models.CASCADE, related_name='feelers')
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
JobPosition.objects.filter(position=self.position).update(position_status='status')
CodePudding user response:
You can add a separate method to your model. This makes sense as it keeps code related to the model with the model.
class JobPosition(models.Model):
...
position_status = models.CharField(choices=POSITION_STATUS)
def update_position_status(self):
#get the top value of related outreaches
#This is assuming your status choices have integer equivalents, and the 'top' is the highest value
top_feeler = self.feelers.all().order_by("-outreach_status").first()
self.position_status = top_feeler.outreach_status
self.save()
You can then call the update method from the save function of your Outreach model (and other places if necessary without having to repeat it)
class Outreach(models.Model):
...
def save(self, *args, **kwargs):
#save the status so everything is up to date
super().save(*args, **kwargs)
#call the job position update function to re-evaluate the position
self.position.update_position_status()