[Django]-How to know the count of many to many fields and reverse relationship of an random model?

3👍

✅

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()
)

Leave a comment