Samsquanch
Samsquanch

Reputation: 9146

Update FK model DateField after save

I have a person model and a group model, as shown below:

class Person (models.Model):
  name = models.CharField(max_length=75)
  group = models.ForeignKey('Group', blank=True, null=True)

class Group (models.Model):
  name = models.CharField(max_length=100)
  last_join = models.DateField(auto_now = True)

What I would like is when I add a new person to a group, the group's last_join is updated with the current time. Can I do this within the models?

Upvotes: 0

Views: 35

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

Sure, just use a post_save signal on your Person model to update the time of Group. Auto_now is great for updating the last modified date, but that only applies to the model in which it's contained. It isn't aware of changes in state to other, related models.

Upvotes: 2

Related Questions