如何将django国家整合到现有模型中

时间:2016-08-15 10:17:13

标签: python django django-models django-countries

我在生产的数据库中有一个现有的国家/地区类,但我想使用Django_Countries模型来更新我使用的所有国家/地区。

这是现有的模型。它允许用户创建国家/地区并上传其国家/地区的标志

class Country(models.Model):
    name = models.CharField(_("Name"))
    icon = models.ImageField(_("Icon"),upload_to=os.path.join('images', 'flags'))

我想删除用户创建国家/地区的选项,只需选择一个国家/地区。

我无法真正改变现有模型,因为它存在很多依赖关系。我只想将名称和标志添加到现有模型中。

1 个答案:

答案 0 :(得分:0)

最后,最后只是将国家/地区转储到json文件并编写迁移来更新数据库。

def forwards(apps, schema_editor):
    Country = apps.get_model('country', 'Country')
    Region = apps.get_model('country', 'Region')

    Region.objects.filter(id=45).delete()

    with codecs.open(os.path.join(os.path.dirname(__file__), 'countries.json'), encoding='utf-8') as cfile:
    data = json.load(cfile)

    for country, regions in data.items():
        country, created = Country.objects.get_or_create(name=country)


class Migration(migrations.Migration):
    dependencies = [
    ('country', 'previous_migration'),
]

operations = [
    migrations.RunPython(forwards),
]
相关问题