为了账号安全,请及时绑定邮箱和手机立即绑定

django_address 模块是否提供了一种播种初始国家数据的方法?

django_address 模块是否提供了一种播种初始国家数据的方法?

呼如林 2022-07-12 09:41:14
我正在使用 Django 2.0、Python 3.7 和 MySql 5。我最近安装了 django_address 模块。我注意到当我基于我的 models.py 文件运行我的初始迁移时......from django.db import modelsfrom address.models import AddressFieldfrom phonenumber_field.modelfields import PhoneNumberFieldclass CoopType(models.Model):    name = models.CharField(max_length=200, null=False)    class Meta:        unique_together = ("name",)class Coop(models.Model):    type = models.ForeignKey(CoopType, on_delete=None)    address = AddressField(on_delete=models.CASCADE)    enabled = models.BooleanField(default=True, null=False)    phone = PhoneNumberField(null=True)    email = models.EmailField(null=True)    web_site = models.TextField()它创建了一些地址表,包括...mysql> show create table address_country;+-----------------+---------------------------------------------------+| Table           | Create Table                                      |+-----------------+---------------------------------------------------+| address_country | CREATE TABLE `address_country` (                  ||                 |   `id` int(11) NOT NULL AUTO_INCREMENT,           ||                 |   `name` varchar(40) COLLATE utf8_bin NOT NULL,   ||                 |   `code` varchar(2) COLLATE utf8_bin NOT NULL,    ||                 |   PRIMARY KEY (`id`),                             ||                 |   UNIQUE KEY `name` (`name`)                      ||                 | ) ENGINE=InnoDB                                   ||                 | DEFAULT CHARSET=utf8 COLLATE=utf8_bin             |+-----------------+---------------------------------------------------+但是,此表中没有数据。有没有办法获取模块生成的表的种子数据,还是我需要自己挖掘?
查看完整描述

5 回答

?
德玛西亚99

TA贡献1770条经验 获得超3个赞

您可以使用pycountrypackage很容易地自己生成国家/地区。


由于创建code的模型字段Country的最大长度为两个字符,因此您需要使用该alpha_2代码。


我通常对这类事情使用自定义管理命令。也许添加一个检查以查看是否已经创建了任何对象,然后根据需要进行处理。


从外壳使用python manage.py create_countries


from address.models import Country

from pycountry import countries

from django.core.management.base import BaseCommand


class Command(BaseCommand):

    help = 'Initialize Country model'


    def handle(self, *args, **kwargs):

        create_countries = [

            Country(name=country.name[:40], code=country.alpha_2)

            for country in countries

        ]

        Country.objects.bulk_create(create_countries)

        self.stdout.write(f'Created {len(countries)} countries.\n')

如果生产服务器没有运行 Python/Django,那么您可以使用pycountry创建包含相关数据的 CSV 文件。假设您使用的是 PostgreSQL,那么您可以使用该COPY FROM命令来填充数据库。


import csv

from pycountry import countries


with open('countries.csv', mode='w') as countries_file:

    # specify delimiter because some countries have a comma

    writer = csv.writer(countries_file, delimiter='\t')

    writer.writerow(['id', 'name', 'code'])

    writer.writerows([

        [index + 1, country.name, country.alpha_2]

        for index, country in enumerate(countries)

    ])


查看完整回答
反对 回复 2022-07-12
?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

我建议您编写一个简单的管理命令,将pycountry中的数据导入您的地址模型(从此处借用的方法)。pycountry 是 ISO 标准国家/地区列表的包装器 - 即,它与您将获得的国家/地区列表一样规范。


将所有国家/地区填充到您的模型中的管理命令Country如下所示:


import pycountry

from django.core.management.base import BaseCommand, CommandError


from address.models import Country


class Command(BaseCommand):

    help = "Populates address.Country with data from pycountry."


    def handle(self, *args, **options):

        countries = [

            Country(

                code=country.alpha_2,

                name=country.name[:40],  # NOTE - concat to 40 chars because of limit on the model field

            )

            for country in pycountry.countries

        ]


        Country.objects.bulk_create(countries)

        self.stdout.write("Successfully added %s countries." % len(countries))

这将使用 ISO 国家/地区列表填充您的模型。


这里需要注意的是,该address.Country.name字段限制为 40 个字符(这对我来说似乎是一个有问题的设计决定,以及不使国家代码唯一的决定 - ISO 2 字母代码肯定是唯一的),所以上面的脚本截断了适合的名字。如果这对您来说是个问题,我建议您建立自己的地址模型,借用django-address并提高字符限制。


查看完整回答
反对 回复 2022-07-12
?
慕姐4208626

TA贡献1852条经验 获得超7个赞

您可以使用django-countries并在模型中包含 CountryField。这包括对模型的支持和表单的选择字段。

由于这是内置的,因此您可以将其包含在您的模型中,而不必担心播种表格。


查看完整回答
反对 回复 2022-07-12
?
拉丁的传说

TA贡献1789条经验 获得超8个赞

如上所述,您需要自己添加实际数据。您需要准备它并进行一次性上传。如果您只查找国家/地区数据,这是一个很好的来源。还有一个名为django-countries的 django 应用程序,它可以让您拥有更多数据和控件,包括标志、ISO 代码等。另一个具有 3 个字母代码的数据库是IBAN 列表。希望有帮助。



查看完整回答
反对 回复 2022-07-12
?
慕容森

TA贡献1853条经验 获得超18个赞

简单更好。通过 django 文档,您可以创建数据迁移:https ://docs.djangoproject.com/en/3.0/topics/migrations/#data-migrations

假设您的应用名称models.pycoops,请执行以下操作:

第一的:

第二:

  • 添加django_countriesINSTALLED_APPS

第三:

  • 制作一个空的迁移文件:python manage.py makemigrations --empty coops

向前:

  • 编辑迁移文件,例如:vi coops/migrations/0002_auto_20200205_0421.py

  • 文件内容:

# Generated by Django 2.2 on 2020-02-05 04:21


from django.db import migrations



def init_countries(apps, schema_editor):

    from django_countries import countries

    from address.models import Country

    countries = [

        Country(code=code, name=name) for code, name in countries

    ]

    Country.objects.bulk_create(countries)




class Migration(migrations.Migration):


    dependencies = [

        ('coops', '0001_initial'),

    ]


    operations = [

        migrations.RunPython(init_countries),

    ]

第五:


跑python manage.py migrate

迁移后 address_country 表应该有如下数据:


In [1]: from address.models import *


In [2]: Country.objects.all()

Out[2]: <QuerySet [<Country: Afghanistan>, <Country: Albania>, <Country: Algeria>, <Country: American Samoa>, <Country: Andorra>, <Country: Angola>, <Country: Anguilla>, <Country: Antarctica>, <Country: Antigua and Barbuda>, <Country: Argentina>, <Country: Armenia>, <Country: Aruba>, <Country: Australia>, <Country: Austria>, <Country: Azerbaijan>, <Country: Bahamas>, <Country: Bahrain>, <Country: Bangladesh>, <Country: Barbados>, <Country: Belarus>, '...(remaining elements truncated)...']>


In [3]: Country.objects.all().count()

Out[3]: 249


查看完整回答
反对 回复 2022-07-12
  • 5 回答
  • 0 关注
  • 121 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号