简体   繁体   中英

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

Let's say I create several pweewee link models

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 . Let's say that I have an object which can be either a car or a pet . I'm not sure whic, but I know that the owner field is a foreign field. How can I get the parent model of that field?

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. This means, that we can get the field object by:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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