amann amann - 2 years ago 207
Python Question

How to check the type of a many-to-many-field in django?

How can you check the type of a many-to-many-field in django?

I wanted to do it this way:

import django
field.__class__ == django.db.models.fields.related.ManyRelatedManager

This doesn't work, because the class
can't be found.
But if i do
the output is

Why does it refer to a class that doesn't seem to exist and how can i bring it to work?

Many thanks for your help.

Answer Source

If you already have the field instance you can simply do:

if isinstance(field, ManyToManyField):
    pass // stuff

If you only have the related manager instance, you can reverse lookup the field instance:

>>> print fm
<class 'django.db.models.fields.related.ManyRelatedManager'>
>>> print fm.instance._meta.get_field_by_name('fieldnamehere')
(<django.db.models.fields.related.ForeignKey: fieldnamehere>, None, True, False)

This has only been tested on Django 1.5

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download