given a string identifying a Django model I have to obtain the associated object of type <class 'django.db.models.base.ModelBase'>
or None.
I'm going to show my solution, that works fine but looks ugly. I'd be glad to know if there are better options to obtain the same result. Does something like a Django shortcut exist for that? Thanks.
>>> from django.utils.importlib import import_module
>>> model = 'sandbox.models.Category'
>>> full_name = model.split(".")
>>> module_name = ".".join(full_name[:-1])
>>> class_name = full_name[-1]
>>> model = getattr(import_module(module_name), class_name, None)
>>> type(model)
<class 'django.db.models.base.ModelBase'>
There exists a shorcut get_model.
from django.db.models import get_model
And here its signature:
def get_model(self, app_label, model_name, seed_cache=True):
And here how can you use it:
>>> from django.db.models import get_model
>>> model = 'amavisd.models.Domain'
>>> app_label, _, class_name = model.split('.')
>>> model = get_model(app_label, class_name)
>>> type(model)
class 'django.db.models.base.ModelBase'
For django 1.8+ you can use following code
>>> from django.apps import apps
>>> apps.get_model('shop', 'Product')
<class 'shop.models.Product'>
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With