Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import a model in Django given the name

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'>
like image 306
Paolo Avatar asked Apr 04 '11 18:04

Paolo


1 Answers

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'>
>>> 
like image 88
Aldarund Avatar answered Oct 04 '22 04:10

Aldarund