Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if a django model attribute is of type ManyToMany?

I have a django model in which I am inspecting the fields types and I want to check if a field is a ManyToMany field. When I call the type(attribute) function however, the returned type is a ManyRelatedManager object and not a ManyToManyField. This is a bit of a problem because I can’t use the isinstance(attribute, ManyRelatedManager) because from what I see in the source code, this class is in a closure context and can’t be accessed externally.

How would I check if a field in django is of type ManyToMany?
I checked out this answer but this doesn’t seem to be my scenario, I don’t care what is the model of the ManyToMany I want to know if it is a many to many.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can work with your model:

isinstance(MyModel._meta.get_field('field_name'), ManyToManyField)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading