我的意图是通过使用一些JSON数据进行数据迁移来创建一些初始模型实例。在JSON文件上调用json.load()
时,我正在遍历每个字典及其键。任何带有空格的键都应替换为包含下划线的新字符串。这样做是为了在使用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)
]
答案 0 :(得分:0)
发生这种情况的原因是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)