Search code examples
djangodjango-managers

import RelatedManager from django.db.models.fields.related


I'm trying to do this:

from django.db.models.fields.related import RelatedManager

because I want to be able to test if an object is a related manager ie:

isinstance(obj, RelatedManager)

however I keep getting this error: Error: cannot import name RelatedManager


Solution

  • The related manager classes are created at runtime inside generator functions in django.db.models.fields.related thus you can't import them directly. If you want to check if an object is a related manager for a specific relation you can use isinstance(obj, MyModel.my_relation.__class__). You could also use hasattr to determine if the object has the properties you need (ducktyping) and avoid using isinstance altogether.