How to import a model into Django with the name

for the string identifying the Django model, I should get a related object of type <class 'django.db.models.base.ModelBase'> or None.

I'm going to show my solution, it works great, but it looks ugly. I would be happy to know if there are better options for getting the same result. Is there something like a Django shortcut for this? 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'> 
+4
source share
1 answer

There is a shorcut get_model.

 from django.db.models import get_model 

And here is his signature:

 def get_model(self, app_label, model_name, seed_cache=True): 

And here is how you can 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 the following code

 >>> from django.apps import apps >>> apps.get_model('shop', 'Product') <class 'shop.models.Product'> >>> 
+6
source

Source: https://habr.com/ru/post/1346605/


All Articles