簡體   English   中英

如何通過peewee中的ForeignKeyField從子級調用父方法?

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

我有兩節課:

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()

我初始化數據庫,創建兩個表並嘗試運行B.test_ping() ,但無濟於事。

嘗試更改我將外鍵指定為自引用的方式__A_reference = peewee.ForeignKeyField("self", null=True, backref="Bs") ,但再次沒有用。

試圖看一堆代碼示例,但似乎從來沒有這樣的情況:擁有外鍵的(子)對象實際上是在使用它從父對象中調用某些方法。

我不明白為什么這會造成混淆...訪問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