Django, detect if model field is inherited

236 views Asked by At

I'd like to check if a model field is inherited, similar to Field.is_relation. Is there a way to tell?

I have a model that inherits from MPTTModel and I want a list of the attributes defined directly in the model but not in MPTTModel.

E.g.:

# models.py
class ACoolModel(MPTTModel):
    name = CharField(max_length=128)

Then, something like:

[f.attname for f in ACoolModel._meta.get_fields(False)]

Gives back the fields from MPTTModel as well:

['id', 'name', 'lft', 'rght', 'tree_id', 'level']

But I want it to return:

['id', 'name']
1

There are 1 answers

0
James H. On BEST ANSWER

Resolved using solution suggested in comments:

all_fields = [f.attname for f in ACoolModel._meta.get_fields(False)]
inherited_fields = [f.attname for f in MPTTModel._meta.get_fields(False)]
non_inherited_fields = [field for field in all_fields if field not in inherited_fields]