简体   繁体   English

如何通过peewee中的ForeignKeyField从子级调用父方法?

[英]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. 我初始化数据库,创建两个表并尝试运行B.test_ping() ,但无济于事。

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. 尝试更改我将外键指定为自引用的方式__A_reference = peewee.ForeignKeyField("self", null=True, backref="Bs") ,但再次没有用。

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. 试图看一堆代码示例,但似乎从来没有这样的情况:拥有外键的(子)对象实际上是在使用它从父对象中调用某些方法。

I don't see why this is confusing... accessing B.__A_reference will return the related A instance: 我不明白为什么这会造成混淆...访问B .__ A_reference将返回相关的A实例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM