2

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.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Iustinian Olaru
  • 1,231
  • 1
  • 13
  • 33

1 Answers1

3

You can work with your model:

isinstance(MyModel._meta.get_field('field_name'), ManyToManyField)
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555