B
B
bQ12019-08-30 11:51:45
Django
bQ1, 2019-08-30 11:51:45

How to pass Django model name to a function?

How to pass Django model name to a function?
view:

def get_obj(model_name, id):
    try:
        obj = models.model_name.objects.get(id=id)
    except (ObjectDoesNotExist, ValueError, TypeError):
        obj = None
    return obj

post = self.get_obj('Post', post_id)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2019-08-30
@bQ1

getattr(models, model_name).objects.get(id=id)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question