Django / Python:如何遍历字典中的列表以进行迁移/迁移数据 [英] Django/Python: How to iterate through a list in a dictionary for migration/migrate data

查看:205
本文介绍了Django / Python:如何遍历字典中的列表以进行迁移/迁移数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I’m trying to set up migration files to load values into my tables. I am creating countries/states in my tables. I would like to set it up in a way that I can put each country in its own file, and then run through all the countries on migration. I successfully got all the names in separately, but I’m trying to make it easier.

更新:

感谢您的帮助,我完全按照我想要的方式工作。这是我的最终结果。

Thanks for help, I got it all to work the way I want it to. Here is my end result.

模特:

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,

}

第二个国家/地区档案:

Second country file:

# 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 并编辑迁移文件:

Then I run python3 manage.py makemigrations --empty app and edit the migration file:

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 并在终端中获得结果

Then run python3 manage.py migrate and get results in the terminal

...               # 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 文件并将我的列表更改为:

And when I want to add another country, france, I make a france file and change my list to:

list_of_countries = [

    canada,
    france,
    united_states,

]

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

And any changes I make should stay up to date. Hopefully. Any suggestions, feel free to let me know.

推荐答案

我想你最初尝试接近这个任务的方式就是问题。我想你应该更新你的字典:

I guess the problem the way you initially are trying to approach this task. I think you should update your dictionary:

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

请记住,键应该是不可变对象列表_of_countries中的国家/地区

Keep in mind that a key should be an immutable object.

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

我不确定你想要达到的目标,但如果你提供了更好的描述我可以更新我的答案。

I am not sure what you are trying to achieve, but if you provide a better description I can update my answer.

这篇关于Django / Python:如何遍历字典中的列表以进行迁移/迁移数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆