Search code examples
pythondjangodjango-viewsdjango-context

Best practices for passing model names as strings


I have two different models that I would like to filter similarly by a common field name at different times, so i've written a single context function that handles both models by taking a string as an argument to use as the model name. Right now I'm using eval(), but something in my gut tells me that's a grave error. Is there a more pythonic way to do what I'm describing?

Here's a shortened version of what my code looks like at the moment:

def reference_context(model, value):
    menu = main_menu()
    info = company_info()
    pages = get_list_or_404(eval(model), category = value)

Secondly, is there a way to pass a keyword in a similar fashion, so I could have something along the lines of:

def reference_context(model, category, value):
    menu = main_menu()
    info = company_info()
    pages = get_list_or_404(eval(model), eval(category) = value)

And commentary on any other issue is welcome and greatly encouraged.


Solution

  • If they are come from the same module (models.py), you can use getattr to retrieve the model class, and kwargs (a dict with double asterisk) this way:

    from myapp import models
    
    def reference_context(model, value):
        menu = main_menu()
        info = company_info()
        pages = get_list_or_404(getattr(models, model), **{category: value})