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

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

I wanted to do this as follows:

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

This does not work because the class ManyRelatedManagercannot be found. But if I do field.__class__, the output will bedjango.db.models.fields.related.ManyRelatedManager

Why does this apply to a class that does not seem to exist, and how can I make it work?

Many thanks for your help.

+5
source share
4 answers

If you already have an instance of the field, you can simply do:

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

If you have only the associated manager instance, you can cancel the search for 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 been tested only on Django 1.5.

+5
source

.

field.__class__.__name__ == 'ManyRelatedManager'
+12

, , , _meta ! _meta.fields _meta.many_to_many!

- :

field_class = [f for f in yourmodel._meta.many_to_many if f.name=='yourfield'][0].__class__
0

( Django 1.11)

, . , JobTemplate - , credentials - :

>>> JobTemplate._meta.get_field('credentials').__class__
 django.db.models.fields.related.ManyToManyField

, _meta ?

>>> JobTemplate.objects.first()._meta.get_field('credentials').__class__
django.db.models.fields.related.ManyToManyField

.

, , , , , . :

>>> JobTemplate.objects.first().credentials
<django.db.models.fields.related_descriptors.ManyRelatedManager at 0x6f9b390>

, OP.

, Credential. , !

>>> isinstance(JobTemplate.objects.first().credentials, Credential.objects.__class__)
True

ManyToMany , . , get_field('credentials'), . isinstance , . , - , , "quacks", ManyToMany .

0

All Articles