On Thu, 2007-03-15 at 08:37 +1100, Malcolm Tredinnick wrote:
> On Wed, 2007-03-14 at 20:26 +0000, Norjee wrote:
> > Imagine the following model:
> > 
> > class Article(models.Model):
> >     title = models.IntegerField()
> > 
> > Then when you do case 1):
> > art = Article.objects.get(pk=1)
> > art.title = "New title"
> > art.save()
> > 
> > or case 2):
> > art = Article.objects.get(pk=1)
> > art.save()
> > 
> > Is there a way that the model, before saving, knows whether the title
> > (or any other field) has been reassigned? I need to know because for a
> > datefield I want to use now if no explicit date is given, otherwise
> > the given date.
> 
> There's no one-line method, but it's pretty easy to do: write a custom
> save() method on the Article class that retrieves the instance again and
> compares the fields. Something like
> 
>         def save(self):
>             if self.id:
>                 original = Article.objects.get(id=self.id)
>                 # Compare fields you care about
>             super(Article, self).save()

It just occurred to me that there's another way to do this if you're
going to need it fairly often...

Write your own __init__() method on the Article class and make sure you
call Model.__init__ (or super(Article, self).__init__) as the very first
thing. The Model __init__ will initialise your class by loading any data
into the attributes. Then your own __init__ code can copy those original
values to another attribute somewhere in the object. Inside your save()
method, you compare the attributes you are saving to the ones you copied
aside in the __init__ method to work out any differences.

Normally we don't need to write __init__ methods on models, so I wasn't
thinking along these lines. Whilst pushing the vacuum cleaner around the
living room just now I realised I'd missed something obvious.

Regards,
Malcolm


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to