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

我正在使用 Django 2.0、Python 3.7 和 MySql 5。我最近安装了 django_address 模块。我注意到当我基于我的 models.py 文件运行我的初始迁移时......


from django.db import models


from address.models import AddressField

from phonenumber_field.modelfields import PhoneNumberField



class 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             |

+-----------------+---------------------------------------------------+

但是,此表中没有数据。有没有办法获取模块生成的表的种子数据,还是我需要自己挖掘?


呼如林
浏览 122回答 5
5回答

德玛西亚99

您可以使用pycountrypackage很容易地自己生成国家/地区。由于创建code的模型字段Country的最大长度为两个字符,因此您需要使用该alpha_2代码。我通常对这类事情使用自定义管理命令。也许添加一个检查以查看是否已经创建了任何对象,然后根据需要进行处理。从外壳使用python manage.py create_countriesfrom address.models import Countryfrom pycountry import countriesfrom django.core.management.base import BaseCommandclass 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 csvfrom pycountry import countrieswith 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)    ])

尚方宝剑之说

我建议您编写一个简单的管理命令,将pycountry中的数据导入您的地址模型(从此处借用的方法)。pycountry 是 ISO 标准国家/地区列表的包装器 - 即,它与您将获得的国家/地区列表一样规范。将所有国家/地区填充到您的模型中的管理命令Country如下所示:import pycountryfrom django.core.management.base import BaseCommand, CommandErrorfrom address.models import Countryclass 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并提高字符限制。

慕姐4208626

您可以使用django-countries并在模型中包含 CountryField。这包括对模型的支持和表单的选择字段。由于这是内置的,因此您可以将其包含在您的模型中,而不必担心播种表格。

拉丁的传说

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

慕容森

简单更好。通过 django 文档,您可以创建数据迁移:https ://docs.djangoproject.com/en/3.0/topics/migrations/#data-migrations假设您的应用名称models.py是coops,请执行以下操作:第一的:pip install django-countries(我更喜欢 pipenv 安装)https://github.com/SmileyChris/django-countries第二:添加django_countries到INSTALLED_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:21from django.db import migrationsdef init_countries(apps, schema_editor):&nbsp; &nbsp; from django_countries import countries&nbsp; &nbsp; from address.models import Country&nbsp; &nbsp; countries = [&nbsp; &nbsp; &nbsp; &nbsp; Country(code=code, name=name) for code, name in countries&nbsp; &nbsp; ]&nbsp; &nbsp; Country.objects.bulk_create(countries)class Migration(migrations.Migration):&nbsp; &nbsp; dependencies = [&nbsp; &nbsp; &nbsp; &nbsp; ('coops', '0001_initial'),&nbsp; &nbsp; ]&nbsp; &nbsp; operations = [&nbsp; &nbsp; &nbsp; &nbsp; migrations.RunPython(init_countries),&nbsp; &nbsp; ]第五:跑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
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python