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'
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>')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With