繁体   English   中英

`peewee` 如何获取外键的父 model

[英]`peewee` how to get the parent model of a foreign key

假设我创建了几个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 假设我有一个 object 可以是carpet 我不确定哪个,但我知道owner字段是一个外国字段。 如何获得该字段的父 model?

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

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

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

现在,要获取 model 及其相关字段,我们需要执行owner_field.rel_modelowner_field.rel_field

暂无
暂无

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

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