Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

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)
like image 642
Sh VavilenT Avatar asked Jan 19 '26 22:01

Sh VavilenT


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()
)
like image 117
Willem Van Onsem Avatar answered Jan 22 '26 13:01

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!