Django/Python:如何迭代字典中的列表以进行迁移/迁移数据

2024-01-09

我正在尝试设置迁移文件以将值加载到我的表中。我正在我的表格中创建国家/州。我想以一种可以将每个国家/地区放入自己的文件中的方式进行设置,然后遍历所有移民国家/地区。我成功地分别输入了所有的名字,但我正在努力让它变得更容易。

UPDATE:

感谢您的帮助,我让一切都按照我想要的方式工作。这是我的最终结果。

models:

class Country(models.Model):
    country_code = models.CharField(
        primary_key=True,
        max_length=3,
        verbose_name='Country Code',
        help_text='3 Letter Country Code',
        )
    country_name = models.CharField(
        "Country Name",
        max_length=30,
        unique=True,
        )

class State(models.Model):
    key = models.AutoField(
        primary_key=True,
        )
    country = models.ForeignKey(
        'Country',
        on_delete=models.CASCADE,
        verbose_name='Country',
        help_text='State located in:'
        )
    state_name = models.CharField(
        "State or Province",
        max_length=100,
        )
    state_code = models.CharField(
        "State Code",
        max_length=30,
        help_text='Mailing abbreviation'
        )

迁移数据文件:

"""
Canada migration information.
    Stored in dictionary = canada

copy into migration_data_migrate_countries
    from .migration_country_Canada import canada

Models:
    Country
    State
"""

# Country
import_country = ['CAN', 'CANADA',]

# State
import_states = [

    ['AB', 'ALBERTA'],
    ['BC', 'BRITISH COLUMBIA'],
    ['MB', 'MANITOBA'],
    etc...

]

# 'import' into migration file
canada = {

    'country': import_country,
    'states': import_states,

}

第二个国家文件:

# Country
import_country = ['USA', 'UNITED STATES',]

# State
import_states = [

    ['AL', 'ALABAMA'],
    ['AK', 'ALASKA'],
    ['AZ', 'ARIZONA'],
    etc...

]

# 'import' into migration file
united_states = {

    'country': import_country,
    'states': import_states,

    }

导入方法:

# Keep imports alphabetized by country name.
from .migration_country_Canada import canada
from .migration_country_UnitedStates import united_states

list_of_countries = [

    canada,
    united_states,

]


def migrate_countries(apps, schema_editor):
    Country = apps.get_model('app', 'Country')
    State = apps.get_model('app', 'State')

    for country in list_of_countries:
        import_country = country['country']
        states = country['states']

        current_country = Country.objects.get_or_create(
                                country_code=import_country[0],
                                country_name=import_country[1]
                                )

        # False = already exists. True = created object.
        print(import_country, current_country)

        for s in states:
            state_country = Country.objects.get(
                                country_code=import_country[0])
            state = State.objects.get_or_create(
                            country=state_country,
                            state_code=s[0],
                            state_name=s[1],
                            )

            # False = already exists. True = created object.
            print(s, state)

然后我跑python3 manage.py makemigrations --empty app并编辑迁移文件:

from django.db import migrations

from app.migration_countries.migration_data_migrate_countries import *


class Migration(migrations.Migration):

    dependencies = [
        ('app', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(migrate_countries),
    ]

然后运行python3 manage.py migrate并在终端中得到结果

...               # Added Canada first which is why YUKON is False
['YT', 'YUKON'] (<State: State object (75)>, False)
['USA', 'UNITED STATES'] (<Country: Country object (USA)>, True)
['AL', 'ALABAMA'] (<State: State object (76)>, True)
...

当我想添加另一个国家时,france,我做了一个france文件并更改我的list to:

list_of_countries = [

    canada,
    france,
    united_states,

]

我所做的任何更改都应该保持最新。希望。如有任何建议,请随时告诉我。


我猜想问题出在你最初尝试完成这项任务的方式上。我认为你应该更新你的字典:

canada = {
    'country': import_country,
    'states': import_states,
}

请记住,键应该是不可变的对象。

for country in list_of_countries:
    import_country = country['country']
    states = country['states']

    current_country = Country.objects.get_or_create(
                                country_code=c[0],
                                country_name=c[1]
                                )
    current_country.states = states

我不确定您想要实现什么目标,但如果您提供更好的描述,我可以更新我的答案。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Django/Python:如何迭代字典中的列表以进行迁移/迁移数据 的相关文章

随机推荐