Миграции Django создают объект с внешним ключом

У меня есть три таблицы по одной стране, штату и городу. `

class Country(BaseModel):
    name = models.CharField(max_length=128)
    code = models.CharField(max_length=2, unique=True)
    isd_code = models.CharField(max_length=8)

class State(BaseModel):
    country = models.ForeignKey("geo.Country", on_delete=models.CASCADE)
    name = models.CharField(max_length=256)
    code = models.PositiveIntegerField(blank=True, null=True)

class City(BaseModel):
    name = models.CharField(max_length=128)
    country = models.ForeignKey("geo,Country", on_delete=models.CASCADE)
    state = models.ForeignKey("geo.State", on_delete=models.CASCADE)

I have crete objecte throw migration country and state.

def import_legacy_countries(apps, schema):
    Country = apps.get_model('geo', 'Country')

    for country in Country.objects.all():
        country.delete()

    with open('legacy_data/CountryDetails.csv', mode='r') as file:
        # reading the CSV file
        csvFile = csv.reader(file)

        # displaying the contents of the CSV file
        for row in csvFile:
            Country.objects.create(
                name=row[1],
                code=row[2]
            )

def import_legacy_states(apps, schema):
    Country = apps.get_model('geo', 'Country')
    State = apps.get_model('geo', 'State')

    country_cache = {}

    missing_country_codes = []
    non_unique_country_codes = []

    with open('legacy_data/State.csv', mode='r') as file:
        # reading the CSV file
        csvFile = csv.reader(file)

        # displaying the contents of the CSV file
        for row in csvFile:
            country_code = row[1]

            if country_code in country_cache:
                country = country_cache[country_code]
            else:
                try:
                    country = Country.objects.get(code=country_code)
                    country_cache[country_code] = country
                except Country.DoesNotExist:
                    missing_country_codes.append(country_code)
                except Country.MultipleObjectsReturned:
                    non_unique_country_codes.append(country_code)
            State.objects.create(
                name=row[3],
                country=country
            )

        if len(missing_country_codes) + len(non_unique_country_codes):
            print('Missing:')
            pprint(missing_country_codes)
            print('Non Unique:')
            pprint(non_unique_country_codes)
            raise Exception('Missing or non unique country present...')

`

Теперь я хочу добавить все данные о стране и штате в таблицу city страна FK, штат Fk пожалуйста, помогите мне, как мне это сделать.

пожалуйста, подскажите, как мне создать объект страна и государство таблица все данные в город таблица страна и государство FK

Вернуться на верх