Django/Python:如何遍历字典中用于迁移/迁移数据的列表。

时间:2022-11-13 20:21:13

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.

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

UPDATE:

更新:

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

谢谢你的帮助,我把一切都按我想要的方式进行了。这是我的最终结果。

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'
        )

Migration Data files:

迁移数据文件:

"""
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,

    }

import method:

导入方法:

# 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)

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

然后运行python3管理。py移民-空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),
    ]

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

然后运行python3管理。py迁移并在终端中获得结果

...               # 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)
...

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.

我做的任何改变都应该是最新的。希望。有什么建议,尽管告诉我。

1 个解决方案

#1


1  

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,
}

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.

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

#1


1  

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,
}

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.

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