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)
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)
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)
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)