Select multiple rows from database in views.py and send it as array to html page

Viewed 212

I want to select multiple rows in database in Django view and send it as an array to my html page.

views.py

def report_template(request, pk):
    template_list = AddScore.objects.filter(template_name=pk)
    context = {'Template': template_list}
    return render(request, 'myapp/report_template.html', context)

models.py

class AddScore(models.Model):
    score = models.CharField(max_length=100, primary_key=True, default='', blank=True)
    client_name = models.CharField(max_length=300, blank=True)
    template_name = models.CharField(max_length=100, blank=True)

I want the result to be like

data = [
    ['client_name1', '37.54'],
    ['client_name2', '33.54']
]
1 Answers

QuerySet.values_list() is exactly what you need.

Let's say we have 3 records

>>> for obj in AddScore.objects.all():
...     print(obj.__dict__)
... 
{'score': '37.54', 'client_name': 'client_name1', 'template_name': 'some_template1'}
{'score': '33.54', 'client_name': 'client_name2', 'template_name': 'some_template1'}
{'score': '35.53', 'client_name': 'client_name3', 'template_name': 'some_template2'}

And we're looking for this template

>>> pk = 'some_template1'

Use values_list() to have a QuerySet that would include all fields

>>> AddScore.objects.filter(template_name=pk).values_list()
<QuerySet [('37.54', 'client_name1', 'some_template1'), ('33.54', 'client_name2', 'some_template1')]>

Use values_list(*fields) to have a QuerySet that would include the targeted fields only

>>> AddScore.objects.filter(template_name=pk).values_list('client_name', 'score')
<QuerySet [('client_name1', '37.54'), ('client_name2', '33.54')]>

If what you need is a list object instead of a QuerySet object, just convert it to list

>>> qs = AddScore.objects.filter(template_name=pk).values_list('client_name', 'score')
>>> 
>>> list(qs)  # list of tuples
[('client_name1', '37.54'), ('client_name2', '33.54')]
>>> 
>>> list(map(list, qs))  # list of lists
[['client_name1', '37.54'], ['client_name2', '33.54']]
Related