Account Options

  1. Sign in
The old Google Groups will be going away soon, but your browser is incompatible with the new version.
Google Groups Home
« Groups Home
Message from discussion dynamic upcast
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
 
From:
To:
Cc:
Followup To:
Add Cc | Add Followup-to | Edit Subject
Subject:
Validation:
For verification purposes please type the characters you see in the picture below or the numbers you hear by clicking the accessibility icon. Listen and type the numbers you hear
 
Carl Meyer  
View profile  
 More options Oct 23 2008, 12:32 pm
From: Carl Meyer <carl.j.me...@gmail.com>
Date: Thu, 23 Oct 2008 09:32:13 -0700 (PDT)
Local: Thurs, Oct 23 2008 12:32 pm
Subject: Re: dynamic upcast
Hi harold,

On Oct 23, 9:27 am, dadapapa <dadap...@googlemail.com> wrote:

> If by "save a derived object from a parent instance" you mean that
> the method that saves the object is defined in the parent class,
> than this should not cause a problem, since type(self) will
> dynamically identify the object as being of the derived type,
> so final_type gets initialized correctly. Then again, I might have
> misunderstood your problem.

Sorry, I wasn't clear.  You may have a BaseClass instance that is
"really" a DerivedClass, and if you ever call save() from that
BaseClass instance (without casting it to a DerivedClass first), the
recipe will break.  Code is clearer:

>>> d = DerivedClass.objects.create()
>>> d.final_type

<ContentType: derived class>
>>> d2 = BaseClass.objects.all()[0]
>>> d2.final_type

<ContentType: derived class>
>>> d2.save()
>>> d2.final_type

<ContentType: base class>

The fix is just to add an "if not self.id" in the save() method, so
the "final_type" is only set once, at creation time, not on every
save:

    def save(self, *args, **kwargs) :
        if not self.id:
            self.final_type =
ContentType.objects.get_for_model(type(self))
        super(BaseClass, self).save(*args)

Carl


 
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.