python - 初始数据创建因数据迁移而失败
问题描述
我的意图是通过一些 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)
]
解决方案
它发生是因为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)
推荐阅读
- cordova-plugins - 错误:您的系统路径上未安装 Cordova 命令行界面
- electron - 是否可以与其他程序界面交互?
- java - 如何检查一年中的月份是否为一月
- javascript - 我可以更改链接的 div
- qt - 在 QOpenGLWidget 上使用 Qt5 小部件而不过度绘制?
- java - 我的 try catch 功能无法按预期工作
- javascript - React 组件渲染两次
- flutter - iconfont:如何让iconfont在flutter中工作
- c - 读取现有文件以在c中处理数据
- ios - Mapbox iOS:打开设备定位服务后未显示用户位置