0

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']
SkillSet12345
  • 881
  • 3
  • 14
  • 25
  • 6
    You should either use Django's built-in serializers, or (preferably) the Django REST Framework. – Daniel Roseman Jun 01 '18 at 08:11
  • Thanks. I'm still learning Django and am not familiar with either. Will look these up. – SkillSet12345 Jun 01 '18 at 08:12
  • I'm struggling with this, every answer I've tried on similar questions such as https://stackoverflow.com/a/31994176/3219210 still throws up the same error. Please could elaborate a bit further? – SkillSet12345 Jun 01 '18 at 08:32
  • As apparent from your output, add ["amount"] like coin_amount = [Portfolio.objects.filter(user = request.user, coin = key['coin']).values('amount')["amount"] for key in coin_sell_options] This will however give you a list of list. – Sayok88 Jun 01 '18 at 08:50
  • To flatten use coin_amount = [item for sublist in coin_amount for item in sublist] – Sayok88 Jun 01 '18 at 08:52
  • Adding ["amount"] like that results in TypeError – SkillSet12345 Jun 01 '18 at 09:14

1 Answers1

1

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)
SkillSet12345
  • 881
  • 3
  • 14
  • 25
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118