Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve a Django model class dynamically?

Without having the full module path of a Django model, is it possible to do something like:

model = 'User' [in Django namespace] model.objects.all() 

...as opposed to:

User.objects.all(). 

EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g.,

model = django.authx.models.User 

Without Django returning the error:

"global name django is not defined." 
like image 824
thebossman Avatar asked Jan 04 '09 22:01

thebossman


People also ask

Can we inherit model in Django?

Models inheritance works the same way as normal Python class inheritance works, the only difference is, whether we want the parent models to have their own table in the database or not. When the parent model tables are not created as tables it just acts as a container for common fields and methods.

What is def __ str __( self in Django?

def str(self): is a python method which is called when we use print/str to convert object into a string. It is predefined , however can be customised.

How do I find models in Django?

In Django 1.7+ it is better to use get_model() on the Django app registry, which is available via django. apps. apps. get_model(model_name) .

What is __ Str__ in Django model?

The __str__() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object.


2 Answers

I think you're looking for this:

from django.db.models.loading import get_model model = get_model('app_name', 'model_name') 

There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.)

Update for Django 1.7+: According to Django's deprecation timeline, django.db.models.loading has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in Alasdair's answer, In Django 1.7+, there is an applications registry. You can use the apps.get_model method to dynamically get a model:

from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') 
like image 182
Daniel Naab Avatar answered Sep 25 '22 23:09

Daniel Naab


For Django 1.7+, there is an applications registry. You can use the apps.get_model method to dynamically get a model.

from django.apps import apps MyModel = apps.get_model('app_label', 'MyModel') 
like image 38
Alasdair Avatar answered Sep 24 '22 23:09

Alasdair