首页 > 解决方案 > 初始数据创建因数据迁移而失败

问题描述

我的意图是通过一些 JSON 数据的数据迁移来创建一些初始模型实例。在调用json.load()JSON 文件时,我正在遍历每个字典及其键。任何带有空格的键都应该被替换为包含下划线的新字符串。这样做是为了在使用Model.create().

应该重构什么以获得预期的结果?

(注意:所有 JSON 对象键都包含空格)

实际结果:并非所有具有空格的键都被包含下划线的新字符串替换。

预期结果:所有具有空格的键都被替换为包含下划线的新字符串。

#models.py

from django.db import models

# Create your models here.

class Item(models.Model):
    name = models.CharField(unique=True, max_length=255)
    image_filename = models.ImageField()
    category_type= models.CharField(max_length=255, blank=True)
    color = models.CharField(max_length=255, blank=True)
    current_condition = models.CharField(max_length=255, blank=True)

    def __str__(self):
        return self.name
#data migration

# Generated by Django 2.2.7 on 2019-11-30 23:21
import json
from django.db import migrations

def create_items(apps, schema_editor):
    Item = apps.get_model('items', 'Item')
    with open('my_file', 'r', encoding='utf-8') as data_file:
        uploaded_item_data = json.load(data_file)
        for item_dict in uploaded_minerals_data:
            item_name_data = item_dict.keys()
            for name in item_name_data:
                if " " in name:
                    value = item_dict.pop(name)
                    new_name = name.replace(" ", "_")
                    item_dict[new_name] = value
                else:
                    continue
            Item.objects.create(**mineral_dict)

class Migration(migrations.Migration):

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

    operations = [
        migrations.RunPython(create_minerals)
    ]

标签: pythondjango

解决方案


它发生是因为unicode space

您可以使用isspace方法或使用re.sub的正则表达式来解决此问题,如下所示:

import re
test_string = "test string"
out1 = re.sub('\s','_', test_string)
print(out1)

out2 = str().join(['_' if x.isspace() else x for x in test_string])
print(out2)

推荐阅读