Med
Med

Reputation: 69

why update a field in related model on save doesn't work in django?

I'm a bigginer to Django. I have the following two models:

class Case(models.Model):
    location = models.CharField()
    caseStatus = models.ForeignKey(CaseStatus, on_delete=models.CASCADE)

class StatusRecord(models.Model):
    case = models.ForeignKey(Case, on_delete=models.CASCADE, null=True, blank=True)
    caseStatus = models.ForeignKey(CaseStatus, on_delete=models.CASCADE)

    def save(self, *args, **kwargs):
        Case.objects.filter(pk=self.case_id).update(caseStatus=F('caseStatus'))
        super().save(*args, **kwargs) 

I'm trying to update the caseStatus field in the Case Model when user create new record of StatusRecord Model. I have overridden the save function . but the field caseStatus in Case Model never updated. Thank you

Upvotes: 1

Views: 39

Answers (1)

wfehr
wfehr

Reputation: 2225

The problem might be that F('caseStatus') uses the current value of the Case-object. So basically you are updating the value with itself (hope it is clear what I mean).

If you do the following it will work:

Case.objects.filter(pk=self.case_id).update(caseStatus=self.caseStatus)

Upvotes: 2

Related Questions