How do you handle inheritance ?

14 views
Skip to first unread message

Thijs Maenhout

unread,
May 3, 2021, 4:59:52 AM5/3/21
to peewee-orm
Hi,

We recently started implementing peewee in our projects.  Right now we are very happy with it.  But now we are bumping on some fundamental questions, we need to solve.

Our projects are customer dependend.  Therefore we have a basemodel that consists of several "base'" classes.  A base class should be extended by custom logic / extra fields depending on the exact customer / project.  

I was testing with the following code.  As you can see, Person.select().count(), will only return 1.  After inspecting the database, i could see there is only row inserted in the Person table, though SpecialPersion is a Person too.  So all logic that is handled in my baseproject wouldn't be aware of any customisations.  

So how would you solve this?  All suggestions are really appreciated.  thanks! 

class BaseModel(Model):
    class Meta:
        database = database
        schema_manager_class = MSSQLSchemaManager
        only_save_dirty = True
        
class Person(BaseModel):
    id = AutoField()
    name=CharField()

    def greet(self):
        print "Hi my name is %s" % (self.name)
            
class SpecialPerson(Person):

    def greet(self):
        print "Hi my name is %s, I'm special !" % (self.name)
        
def create_tables():
    with database:
        database.create_tables([Person, SpecialPerson])

#Drop Tables
database.drop_tables([Person, SpecialPerson])

#Recreate all tables
create_tables()

Person.create(name="Bar")
SpecialPerson.create(name="Foo")

print Person.get().greet()
print SpecialPerson.get().greet()

print SpecialPerson.select().count()
print Person.select().count()




Charles Leifer

unread,
May 3, 2021, 8:51:29 AM5/3/21
to peewe...@googlegroups.com
In peewee every model class corresponds to a database table. Person and SpecialPerson are two separate tables. There is no implicit joining of multiple tables like you might have in Django, for example.

If you have the same table structure and just need different python-level behavior, I'd suggest abstracting that into a different layer than the model class itself.

--
You received this message because you are subscribed to the Google Groups "peewee-orm" group.
To unsubscribe from this group and stop receiving emails from it, send an email to peewee-orm+...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/peewee-orm/23d38e4c-323b-4e61-8ac4-b7549f939737n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages