Search code examples
djangodjango-models

Exclude related fields in model._meta.get_fields()


I have a model currently defined like this:

class Category(models.Model):
    ID = models.AutoField()
    name = models.CharField()
    desc = models.CharField()

Another model Subcategory has a ForeignKey defined on Category.

When I run:

Category._meta.get_fields()

I get:

(<ManyToOneRel: siteapp.subcategory>, <django.db.models.fields.AutoField: ID>, <django.db.models.fields.CharField: name>, <django.db.models.fields.CharField: desc>)

However, I don't want the ManyToOneRel fields; I just want the others.

Currently, I am doing something like this:

from django.db.models.fields.reverse_related import ManyToOneRel
field_list = []
for field in modelClass._meta.get_fields():
    if not isinstance(field, ManyToOneRel):
        field_list.append(field)

However, is there a better way to do this, with or without using the model _meta API?


Solution

  • You could use the concrete_fields property.

    Category._meta.concrete_fields
    

    However this is an internal Django API, and it may be better to use get_fields() with your own filtering, even though it may be a little more verbose.