0

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?

Boris Gorelik
  • 29,945
  • 39
  • 128
  • 170

1 Answers1

0

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

Boris Gorelik
  • 29,945
  • 39
  • 128
  • 170