On 12/11/06, jerf <[EMAIL PROTECTED]> wrote:
> Is there a way to "catch" a property change so I can run some code at
> the time?
>
> Example:
>
> --------
> class Entry(models.Model):
>     ...
>     post_date = models.DateTimeField(...)
>     posted = models.BooleanField(...)
>
> e = Entry.create()
> e.save()
> e.posted = True
> --------
>
> I want to be able to run some code on the last line to automatically
> update 'post_date' at that time.
>
> It would also be acceptable to do this in a .save() override, but I
> can't find a (documented/supported) way to access the old value to
> compare it against the new value at that time.
>
> This would cleanly solve several problems for me, many of which are
> more complicated and tricky than this minimal example.

Hi Jerf,

You can simply write a set_posted() method, like so:

class Entry(models.Model):
    post_date = models.DateTimeField(...)
    posted = models.BooleanField(...)

    def set_posted(self, new_value):
        if new_value != self.posted:
            self.post_date = datetime.datetime.now()

This won't work with the admin interface, because it wouldn't know
about your set_posted() method. With that said, you might be able to
use Python properties, but I have never tried that and am not sure
whether it would work. If it did work, you could do this:

class Entry(models.Model):
    post_date = models.DateTimeField(...)
    posted = models.BooleanField(...)

    def set_posted(self, new_value):
        if new_value != self.posted:
            self.post_date = datetime.datetime.now()
    posted = property(set_posted)

...and any time you set the "posted" attribute, it would call
set_posted() behind the scenes. Like I said, though, I'm not sure
whether that would work with the way models are currently implemented.
(But if not, let's go ahead and fix that!)

Adrian

-- 
Adrian Holovaty
holovaty.com | djangoproject.com

--~--~---------~--~----~------------~-------~--~----~
 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