我如何使用我的 Django 模型获得每个国家/地区的产品数量
how can i get the number of products in each countries using my django models
我在 Django 中有一个模型,我需要一种方法来获取每个国家/地区的产品数量,以便我可以使用它来绘制图表。
注意: 我在我的应用程序中使用了 django-countries 包
models.py
from django.db import models
from django_countries.fields import CountryField
class Product(models.Model):
name = models.CharField(max_length=36) user = models.ForeignKey(User, on_delete=models.CASCADE)
is_favourite = models.ManyToManyField(User, related_name='favourite', blank=True)
country = CountryField(blank_label='(select country)')
我希望结果类似于:
美国:5
不良:20
SA: 8
等等,所以我可以用它来绘制图表。
您可以使用 .annotate(…)
[Django-doc]:
from django.db.models import Count
Product.objects.values('country').annotate(
<b>number=Count('pk')</b>
).order_by('country')
这将使 QuerySet
看起来像:
<QuerySet [
{'country': 'NG', 'number': 20},
{'country': 'SA', 'number': 8},
{'country': 'US', 'number': 5}
]>
我们可以将其转换为将国家映射到相应数字的字典:
from django.db.models import Count
qs = Product.objects.values('country').annotate(
number=Count('pk')
).order_by('country')
result = {
<b>q['country']: q['number']</b>
for q in qs
}
我在 Django 中有一个模型,我需要一种方法来获取每个国家/地区的产品数量,以便我可以使用它来绘制图表。
注意: 我在我的应用程序中使用了 django-countries 包
models.py
from django.db import models
from django_countries.fields import CountryField
class Product(models.Model):
name = models.CharField(max_length=36) user = models.ForeignKey(User, on_delete=models.CASCADE)
is_favourite = models.ManyToManyField(User, related_name='favourite', blank=True)
country = CountryField(blank_label='(select country)')
我希望结果类似于: 美国:5 不良:20 SA: 8
等等,所以我可以用它来绘制图表。
您可以使用 .annotate(…)
[Django-doc]:
from django.db.models import Count
Product.objects.values('country').annotate(
<b>number=Count('pk')</b>
).order_by('country')
这将使 QuerySet
看起来像:
<QuerySet [
{'country': 'NG', 'number': 20},
{'country': 'SA', 'number': 8},
{'country': 'US', 'number': 5}
]>
我们可以将其转换为将国家映射到相应数字的字典:
from django.db.models import Count
qs = Product.objects.values('country').annotate(
number=Count('pk')
).order_by('country')
result = {
<b>q['country']: q['number']</b>
for q in qs
}