I have written a function in Django to look up an object based on its type that works akin to the following:
def lookup(modelType, item_id):
try:
return eval(modelType).objects.get(pk=item_id)
except ObjectDoesNotExist:
return None
lookup(Course, 14) should return Course.objects.get(pk=14) if there is a Course object with ID 14.
Is this function feasible to write? Thank you.
If you want to use
lookup(Course, 14)then do this.If you want to keep using the function you wrote, then you have to pass the model as a string.
lookup( "Course", 14)Also.
return Noneis a very bad idea. It’s usually much better to use exceptions properly.