简体   繁体   English

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

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

Let's say I create several pweewee link models假设我创建了几个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 
        

As you can see, both Car and Pet models are connected to a Person .如您所见, CarPet模型都连接到Person Let's say that I have an object which can be either a car or a pet .假设我有一个 object 可以是carpet I'm not sure whic, but I know that the owner field is a foreign field.我不确定哪个,但我知道owner字段是一个外国字段。 How can I get the parent model of that field?如何获得该字段的父 model?

OK, I managed to find the answer.好的,我设法找到了答案。

obj._meta.fields will give us a dictionary, where the key is the field name and the value is the field object. obj._meta.fields会给我们一个字典,其中键是字段名,值是字段 object。 This means, that we can get the field object by:这意味着,我们可以通过以下方式获得字段 object:

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

Now, to get the model and the field it is related to, we need to do owner_field.rel_model and owner_field.rel_field现在,要获取 model 及其相关字段,我们需要执行owner_field.rel_modelowner_field.rel_field

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

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