I have this code in views.py
def prod_aff(request):
queryset =Produit.objects.all()
ca = sortiestk.objects.all().select_related('ref').select_related('codecateg').values_list('ref__codecateg',flat=True).distinct()
ca1 = list(ca)
print ca1
for val in ca1:
pp = sortiestk.objects.select_related('ref').select_related('codecateg').filter(ref__codecateg=val).aggregate(Sum('qtesrt'))
print pp
return render(request, 'produit/produit.html',{'nomc':getnomcat,'produit':queryset})
It displays:
{'qtesrt__sum': 8},
{'qtesrt__sum': 40},
{'qtesrt__sum': 10}
I want to put only the int values in a list. I tried list(pp)
but it only showed [qtesrt__sum , qtesrt__sum ,qtesrt__sum]
.
Try this:
list(pp.values())
This will get you a list of values from pp
, which are exactly the integers that you want. If you run
list(pp)
you get the list of keys because this statement is equivalent to
list(pp.keys())
If you want to get both keys and values of pp
into a list, you can do
list(pp) + list(pp.values())
If you need to flattern the query result on grouping, you can use annotate
instead of aggregate
pp = sortiestk.objects.select_related('ref').select_related('codecateg').filter(ref__codecateg=val).annotate(qtesrt_total=Sum('qtesrt')).values_list('qtesrt_total', flat=True)
output will be:
[8,40,10]
根据文档QuerySet ,您可以仅使用list()
将查询转换为列表。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.