Iustinian Olaru
Iustinian Olaru

Reputation: 1337

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.

Upvotes: 2

Views: 617

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

You can work with your model:

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

Upvotes: 3

Related Questions