views:

84

answers:

3

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 ManyRelatedManager can't be found. But if i do field.__class__ the output is django.db.models.fields.related.ManyRelatedManager

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.

+1  A: 

You should be able to check it as a string.

field.__class__.__name__ == 'ManyRelatedManager'
Brant
Thanks for the quick response! But isn't that a little bit undynamic? Actually, i don't think that the class "ManyRelatedManager" will be ever renamed, but isn't it a little bit sloppy? But however, i think I'll use this answer, becuase it is more performant than lazerscience's one. Thanks!
amann
A: 

I'm not quite sure what you are trying to achieve, but i guess you should better look into your model's _meta attribute for determining the field class! check out _meta.fields and _meta.many_to_many!

You could do something like:

field_class = [f for f in yourmodel._meta.many_to_many if f.name=='yourfield'][0].__class__
lazerscience
+1  A: 

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

if isinstance(field, ManyToManyField):
    pass // stuff
Béres Botond
This would be the perfect way, but i don't know how to get the field-instance of a many-to-many-field, that is located at the target-model.. if you could help me with this, i'll accecpt your answer :)
amann
I can list all the fields with `object._meta.get_all_field_names()` but the corresponding fieldname isn't accessible via `object._meta.get_field('fieldname')`. I can use the function `object._meta.get_field_by_name('fieldname')` which puts out `(<RelatedObject: projectname:modelname1 related to modelname2>, None, False, True)`. Actually i don't know how to get the field-instance out of that..
amann
got it :).. it is:`object._meta.get_field_by_name("fieldname")[0].field`
amann