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)
3
  • Python is not PHP. Exactly what is "Variable"? Where's it coming from? Commented Apr 12, 2013 at 19:41
  • Variable is just contain a string for the name of the model, so if Variable="ModelA", how can I access ModelA? Commented Apr 12, 2013 at 19:59
  • Actually I am trying to ask the same question as stackoverflow.com/questions/12279846/… Commented Apr 12, 2013 at 20:08

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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)

1 Comment

what if i have like 30 models? If there any way to get objects by name or from string?

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.