On Fri, 2008-09-12 at 11:57 -0700, dadapapa wrote:
> > It does not work at all. For some reason, final_type also gets
> > upcasted to MediaObject?!
> 
> I found the solution, now. The problem was that the __init__ method of
> a Model is also called when objects are restored from the database. So
> when the base class gets initialized by the QueryManager, it
> overwrites final_type with the wrong value. The solution is simple:
> overwrite the save method instead of __init__. Here is a complete
> recipe:
> 
>     class BaseClass(models.Model) :
>         final_type = models.ForeignKey(ContentType)
> 
>         def save(self,*args) :

For absolute robustness, you should also accept **kwargs here. There are
a couple of places in Django's code that will call save() and pass in
force_insert=True, for example, which won't be handled by *args. In
reality, all you need to be able to handle is force_insert and
force_update, but *args and **kwargs are also pretty useful,
particularly if you aren't doing anything with them except passing them
along.

>             self.final_type =
> ContentType.objects.get_for_model(type(self))
>             super(BaseClass,self)save(*args)
> 
>         def cast(self) :
>             return
> self.final_type.get_object_for_this_type(id=self.id)
> 
>     class DerivedClass(ParentClass) :
>         pass
> 
> Here is an example:
> 
>     obj = DerivedClass()
>     obj.save()
> 
>     obj = get_object_or_404(BaseClass, id=3).cast()
>     # obj is now of type DerivedClass

Yes, well done. This looks like the right way to handle this. Glad
somebody's documented it here.

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