0

假设我创建了几个pweewee 链接模型

db = SqliteDatabase('people.db')
class Person(Model):
    name = CharField()
    birthday = DateField()
    class Meta:
        database = db # This model uses the "people.db" database.
class Pet(Model):
    owner = ForeignKeyField(Person, backref='pets')
    name = CharField()
    animal_type = CharField()
    class Meta:
        database = db # this model uses the "people.db" database
class Car(Model):
    owner = ForeignKeyField(Person, backref='cars')
    model = CharField()
    class Meta:
        database = db # this model uses the "people.db" database 
        

如您所见,CarPet模型都连接到Person. 假设我有一个可以是 acar或 a的对象pet。我不确定哪个,但我知道该owner领域是一个外国领域。如何获取该字段的父模型?

4

1 回答 1

0

好的,我设法找到了答案。

obj._meta.fields会给我们一个字典,其中键是字段名,值是字段对象。这意味着,我们可以通过以下方式获取字段对象:

owner_field = obj._meta.fields['owner']

现在,要获取模型及其相关的字段,我们需要owner_field.rel_modelowner_field.rel_field

于 2020-08-06T13:49:27.397 回答