我正在使用一个名为django-countries的 django 包,它可以让我访问世界上的一些国家属性,例如国名、国家代码、国旗等。
似乎默认似乎是国家代码,我想知道如何能够使用国家名称而不是默认的国家代码。
模型.py
from django.db import models
from django_countries.fields import CountryField
class Product(models.Model):
name = models.CharField(max_length=36)
price = models.PositiveIntegerField()
country = CountryField(blank_label='(select country)')
例如在我看来,我有这样的代码
def analyse_market(request):
qs = Product.objects.values('country').annotate(
number=Count('pk')
).order_by('country')
result = {
q['country']: q['number']
for q in qs
}
print(result)
context = {"result":result}
return render(request, 'core/analyse-market.html', context)
这将返回如下结果:
{'AD': 3, 'AR': 5, 'BH': 1, 'FR': 1, 'JP': 1, 'NG': 1, 'NL': 1}
在文档中,他们使用了不同的方法,例如 country.name、country.code、country.flag,我尝试了 country.name,因为它与我的需要有关,但是在我的中使用 country.name 时出现 KeyError意见。