You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django模型的CountryField中使用Alpha3国家代码

让Django CountryField使用ISO Alpha3国家代码

完全可以设置CountryField使用Alpha3标准,需要从模型层和表单层两部分调整:

1. 修改模型中的CountryField

django-countries库的CountryField默认使用Alpha2代码(长度2),只需添加code_length=3参数即可切换为Alpha3:

from django.db import models
from django_countries.fields import CountryField

class Person(models.Model):
    name = models.CharField(max_length=100, null=True, blank=False)
    country = CountryField(
        blank_label='(select country)', 
        default=None, 
        null=True, 
        blank=True,
        code_length=3  # 启用Alpha3格式
    )

添加该参数后,模型会存储长度为3的Alpha3代码(如"USA"对应美国),数据库字段的max_length会自动适配为3。

2. 调整表单的选项与组件

原表单中使用的countries默认返回Alpha2的键值对,需要替换为countries.alpha3来获取Alpha3格式的选项;如果使用CountrySelectWidget,也可以指定code_length=3确保组件渲染正确:

from django import forms
from django_countries import countries
from django_countries.widgets import CountrySelectWidget
# 假设ModelFormSansSuffix是你的自定义基类
from .models import Person

class PersonForm(ModelFormSansSuffix):
    class Meta:
        model = Person
        fields = ["name", "nationality"]
    
    nationality = forms.ChoiceField(
        label="Country",
        help_text="What country are you from?",
        required=True,
        choices=countries.alpha3,  # 使用Alpha3选项
        widget=CountrySelectWidget(code_length=3)  # 组件适配Alpha3
    )

    name = forms.CharField(
        label="Please enter your name",
        max_length=512,
        required=True,
        widget=forms.TextInput()
    )

注意事项

如果数据库中已有Alpha2格式的旧数据,需要编写数据迁移脚本将现有代码转换为Alpha3格式。例如,使用django-countries的Country类进行转换:

# 迁移脚本示例
from django_countries import Country

def convert_alpha2_to_alpha3(apps, schema_editor):
    Person = apps.get_model('your_app', 'Person')
    for person in Person.objects.filter(country__isnull=False):
        person.country = Country(code=person.country).alpha3
        person.save()

内容的提问来源于stack exchange,提问作者James O'Neill

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 13:26:16