Home > front end >  How to check if a django model attribute is of type ManyToMany?
How to check if a django model attribute is of type ManyToMany?

Time:07-13

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.

CodePudding user response:

You can work with your model:

isinstance(MyModel._meta.get_field('field_name'), ManyToManyField)
  • Related