Automatic field update when another field changes

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 of the related fields (i.e. when the first_name is changed and then first_name_ud is set to the current date).

Is there a way to do this automatically or do I need to check which fields have been changed each time I save the object and then update the corresponding "_ud" fields.

Thanks a lot!

+5
source share
2 answers
+3

. , , , , :

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()
0

All Articles