Подсчет списка объектов внутри JSONField в Django - PullRequest
0 голосов
/ 09 марта 2020
class TopCountries(models.Model):
    top_countries = JSONField(null=True)

top_countries - это JSONField

'top_countries': [
  {'country_code': 'AX', 'country_name': 'Åland Islands'},
  {'country_code': 'AL', 'country_name': 'Albania'},
  {'country_code': 'DZ', 'country_name': 'Algeria'}
 ]

Я новичок в расширенных запросах. Я пробовал запрос ниже, но он не дает мне желаемый вывод.

Запрос:

TopCountries.objects.aggregate(Count('top_countries'))

Вывод:

{'top_countries__count': 1}

Желаемый вывод:

{'top_countries__count': 3}

1 Ответ

0 голосов
/ 11 марта 2020

Я думаю, вы должны попробовать annotate вместо aggregate, как показано ниже ...

TopCountries.objects.annotate(Count('top_countries'))
...