[Fixed]-Django add data from queryset to context

1👍

You are using a variable media in function get_context_data, but you don’t have the variable defined in the function. Python variables are bound within function scope so you cannot use it without defining it first.

You shouldn’t query for media in function get_queryset, because get_queryset is meant to get the queryset that ListView will iterate in the template, so it should return only ONE result. If you want extra context, do it in function get_context_data:

def get_context_data(self, **kwargs):
    context = super(LaLista, self).get_context_data(**kwargs)
    # if you didn't define anything special, object_list is the default queryset name
    qs = kwargs['object_list']
    media = qs.aggregate(Avg('A_U'), Max('A_U'), Min('A_U'))

Leave a comment