[Fixed]-Using a variable to extract data from a database in Django

1👍

You can get an idea in this (a little outdated) answer, but the bottom line is that there is no built-in way to access attributes by name getattr()-style in django templates. So you would need to write a custom filter, as described in the django docs:

# app/templatetags/attr_tags.py

from django import template

register = template.Library()

@register.filter
def get_attribute(value, arg):
    return getattr(value, arg)

Now you can do in your template:

{% load attr_tags %}
# ...
{{ data|get_attribute:sortby }}  

# {{ data.sortby }} can't work because that tries to access 
# an attribute named 'sortby', not an attribute with the name
# stored in the context variable of the name 'sortby'

Leave a comment