Search code examples
pythonormparent-childpeewee

How to call a parent method from a child via ForeignKeyField in peewee?


I have two classes:

class A(Base_Model):
    def ping(self):
        print("Ping!")

class B(Base_Model):
    __A_reference = peewee.ForeignKeyField(A, null=True)
    def test_ping(self):
        self.__A_reference.ping()

I initialise the database, create both tables and try running B.test_ping(), but to no avail.

Have tried changing the way I specify the foreign key to be self-referencing __A_reference = peewee.ForeignKeyField("self", null=True, backref="Bs"), but again no use.

Tried looking though a bunch of code examples, but it never seems to be the case that the (child) object that possesses the foreign key is actually using it to call some method from the parent object.


Solution

  • I don't see why this is confusing... accessing B.__A_reference will return the related A instance:

    In [1]: from peewee import *
    
    In [2]: db = SqliteDatabase(':memory:')
    
    In [3]: class A(Model):
       ...:     def ping(self):
       ...:         print('ping')
       ...:     class Meta:
       ...:         database = db
       ...:         
    
    In [4]: class B(Model):
       ...:     a = ForeignKeyField(A)
       ...:     class Meta:
       ...:         database = db
       ...:         
    
    In [5]: db.create_tables([A, B])
    
    In [6]: a = A.create()
    
    In [7]: b = B.create(a=a)
    
    In [8]: b.a.ping()
    ping