Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import and Use django Model Class using variable

Tags:

python

django

I am new to both python and django. First of all I am trying to do database query by using standard django feature . I dont want to use raw SQL.

What i want to achieve:

I want import and use Django Class  dynamically by using variable

like:

dynamic_var = "Note"
#import
from .model import dynamic_var
#query
q = dynamic_var.objects.all()
print(q)

but above code are not working. I know there are some solid reason behind it, because dynamic_var is a String not a Class/model class. But how can i achieve this behavior.

dynamic_var = "Note"
from .model import Note

## Not work but i want to achieve 
info = dynamic_var.objects.all()

# Working
info = Note.objects.all() 

print(info)

Error

AttributeError at /note/
'str' object has no attribute 'objects'
like image 669
coder618 Avatar asked Sep 16 '26 18:09

coder618


1 Answers

You can access to models using below style:

from django.apps import apps

list_of_your_models = apps.get_models()

then you have access to your classes and can find your specific model throw iterate on the list.

There is also an another method in apps.

my_model = apps.get_model('<APP_NAME>', '<MODEL_NAME>')
like image 191
Morteza Afshari Avatar answered Sep 19 '26 17:09

Morteza Afshari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!