views:

147

answers:

2

I have a model with a bunch of different fields like first_name, last_name, etc. I also have fields first_name_ud, last_name_ud, etc. that correspond to the last updated date for the related fields (i.e. when first_name is modified, then first_name_ud is set to the current date).

Is there a way to make this happen automatically or do I need to check what fields have changed each time I save an object and then update the related "_ud" fields.

Thanks a lot!

+2  A: 

Either write Field children that update both fields or use server-side triggers.

Ignacio Vazquez-Abrams
A: 

Thanks for your help. I ended up modifying the model's save method, which I think will work:

def save(self):
    current_date = date.today()
    if self.id:
        try:
            old = UserProfile.objects.get(pk = self.id)
            fields = UserProfile._meta.fields
            for field in fields:
                field_name = field.name
                date_name = field_name + '_ud'
                if not field_name.endswith('_ud') and date_name in fields:
                    if self.__dict__[field_name] != old.__dict__[field_name]:
                        self.__dict__[date_name] = current_date
                        self.date_updated = current_date
        except UserProfile.DoesNotExit:
            pass
    super(UserProfile, self).save()
Gordon