0

In Django, how do I use variables to dynamically use the get_object_or_404 or objects.get like

get_object_or_404(${Variable}, pk=id)

or

${Variable}.objects.get(pk=id)
kli
  • 283
  • 1
  • 5
  • 16
  • Python is not PHP. Exactly what is "Variable"? Where's it coming from? – Daniel Roseman Apr 12 '13 at 19:41
  • Variable is just contain a string for the name of the model, so if Variable="ModelA", how can I access ModelA? – kli Apr 12 '13 at 19:59
  • Actually I am trying to ask the same question as http://stackoverflow.com/questions/12279846/how-to-get-a-model-object-using-model-name-string-in-django – kli Apr 12 '13 at 20:08

2 Answers2

0

No problem, assume that you have two models Post and Comment, You can have this:

from app import models as app_models

dynamic_object = getattr(app_models, 'post')

So you can use it:

dynamic_object.objects.get(pk=id)

or

get_object_or_404(dynamic_object, pk=id)
MostafaR
  • 3,547
  • 1
  • 17
  • 24
  • what if i have like 30 models? If there any way to get objects by name or from string? – kli Apr 12 '13 at 19:57
0

If you assure to pass a Django ORM Model Class in the parameter, get_object_or_404() will work just fine.

def do_something(id,MyDjangoModelObject = None)
    if MyDjangoModelObject:
        get_object_or_404(MyDjangoModelObject, pk=id)

also

MyDjangoModelObject.objects.get(pk=id)
user1802310
  • 126
  • 1
  • 7