简体   繁体   中英

Django: “Object of type 'QuerySet' is not JSON serializable”

I have the following data which I want to pass to JsonResponse.

coin_amount = [Portfolio.objects.filter(user = request.user, coin = key['coin']).values('amount') for key in coin_sell_options]

print(list(coin_amount))

However this returns a ValuesQuerySet , which is not Json serializable:

[<QuerySet [{'amount': Decimal('3.0000000')}]>, <QuerySet [{'amount': 
Decimal('0.1000000')}]>, <QuerySet [{'amount': Decimal('9.0000000')}]>]

That's problematic because I need a list that is JSON serializable.

So I need to get a list like this from my ValuesQuerySet somehow:

['3.0000000', '0.1000000', '9.0000000']

This:

coin_amount = [Portfolio.objects.filter(user=request.user, coin=key['coin']).values('amount') for key in coin_sell_options]

does NOT "returns a ValuesQuerySet", it returns a list of ValuesQuerySet . What you want is the __in lookup operator:

coins = [key['coin'] for key in coin_sell_options]
coin_amount = list(Portfolio.objects.filter(user=request.user, coin__in=coins).values_list('amount', flat=True))
coin_amount = [str(x) for x in coin_amount]

print(coin_amount)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM