开发者

Automatically Update Field when a Different Field is Changed

I have a model with a bunch of different fields like firs开发者_StackOverflow中文版t_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!


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜