2

For example- My query changes for different tables at different instances. I have a string input which tells me which table I have to access at a particular instance, how do I query in django with such varying table?

Usually we query models.Person.objects.filter(), where table_name=Person(which remains same in every query). How do we query when table_name is a variable?

2 Answers 2

2

You can get model by it's name using django apps.get_model method

>>> from django.apps import apps
>>> model_you_want = apps.get_model(app_label='app_name', model_name='model_name_string')
>>> model_you_want.objects.filter()
Sign up to request clarification or add additional context in comments.

Comments

0

with eval you can run a python statement which is in form of string.

I've tested the following on python 3 and django 1.8.x exec keyword also works on python 2

table_name = 'Person'
query = "{0}.objects.all()".format(table_name)
result = eval(query)

5 Comments

Why would you use eval, if django has built-in utilities for retrospection?
Even though eval is slower and this approach requires your model to be imported to make that code work?
Can you suggest a faster approach? @Nick
@Serjick the above approach gives me a Name Error even though the table exists.
@MadhuryaGandi just try my approach in the answer below.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.