How to know the count of many to many fields and reverse relationship of an random model?

Viewed 146

I have an random model:

class Model(models.Model):
      other_field1 = models.SomeField(...)
      m2m_field1 = models.ManyToManyField(...)
      other_field2 = models.SomeField(...)
      m2m_field2 = models.ManyToManyField(...)
      other_field3 = models.SomeField(...)

I want to know the count of fields that correspond to the relation many to many and the count of other fields.

In the example above, I have 2 fields with a many-to-many relationship and 3 other fields.

EDIT

How to calculate the number of reverse relationships?

class OtherModel1(models.Model):
      field = models.ForeginKey(Model)


class OtherModel2(models.Model):
      field = models.ForeginKey(Model)
1 Answers

You can work with the ._meta option, and thus determine the number of items with:

from django.db.models import ManyToManyField
from django.db.models.fields.reverse_related import ForeignObjectRel

number_of_m2m_fields = sum(
    isinstance(m, ManyToManyField) for m in Model._meta.get_fields()
)

number_of_other_fields = sum(
    not isinstance(m, ManyToManyField) for m in Model._meta.get_fields()
)

number_of_reverse_relations = sum(
    isinstance(mto, ForeignObjectRel) for mto in Model._meta.get_fields()
)
Related