artiest
artiest

Reputation: 592

how to convert group by(values) to json - django

i'm trying to convert my grouped by (values in django) data into JsonResponse but it raise this error :

AttributeError: 'dict' object has no attribute 'f_type'

this is my function of loadding json data

def load_cate(request):
    lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total')
    data = []
    for i in lists.values():
    
        item = {
            'wc_type':i.f_type,
            'room_type':i.room_type,
            'beds':i.beds,
            'balcon':i.balcon,
            'total':i.total
        }
        data.append(item)
    
    return JsonResponse({'success':True,'data':data})

is there something i did wrong ? or its different for group by values ?! thanks in advance ..

Upvotes: 0

Views: 412

Answers (1)

Summer
Summer

Reputation: 66

There is no need to loop throught objects. You just need to convert QuerySet into a list. values() will return a QuerySet object which cant be return in a JsonResponse. So just convert into a list.

lists = Room.objects.values('f_type','room_type', 'beds', 'balcon').annotate(total=Count('pk')).order_by('-total')
lists = list(lists)

Upvotes: 1

Related Questions