> > is there a way to have a model subclass avoid the creation of a
> > new database table,and just take its data straight out of the table for
> > its superclass?  
> 
> Right now, I suspect you would also have to manually set Meta.db_table
> and some things like that. However, I strongly suspect each of those are
> fairly straightforward to sort out. We can set db_table automatically
> for such models, if it's not set. We have to make sure the pk property
> talks to the first ancestor model, too. Basically a bunch of fiddly
> stuff, but nothing that's brain surgery levels of difficulty.

Following Malcolm's tips, I have managed to get this working.  After
applying the patch from ticket #3163, I've formulated this class
decorator to make the necessary tweaks to the model's meta info:


    def virtual_inheritance(cls):
        base = cls.__bases__[0]
        pk = base._meta.pk
        #  don't create a new db table
        cls._meta.managed = False
        #  use the superclass table name
        cls._meta.db_table = base._meta.db_table
        #  remove the auto-created parent reference
        cls._meta.local_fields[:] = []
        #  use the superclass primary key
        cls._meta.pk = pk
        cls._meta.parents[base] = pk


Now I can do the following:


    class MyUser(auth.models.User):
        def an_extra_method(self):
           print "hooray!"
    virtual_inheritance(MyUser)


The resulting model behaves exactly as I wanted, adding functionality to
the default User model but taking its data straight out of the auth_user
table.


If I'm feeling inspired tomorrow, I might try to formulate similar logic
as a patch to the ModelBase metaclass, so that subclasses that don't add
any fields will get pure-python inheritance by default.  In the
meantime, I hope some other people might find this trick useful.


  Cheers,

     Ryan


-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
[email protected]        |  http://www.rfk.id.au/ramblings/gpg/ for details

Attachment: signature.asc
Description: This is a digitally signed message part

Reply via email to