5

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'>

1 Answer 1

8

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'>
>>> 
Sign up to request clarification or add additional context in comments.

1 Comment

I cant find get_model in django.db.models in django 2.0 or 1.11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.