python - Django:从 CSV 导入数据 - 元组索引必须是整数或切片,而不是 str
问题描述
在我的 Django APP 中,我想将数据从 CSV 上传到模型。
为了阅读我正在使用pandas
库的数据。但我收到了这个错误:
文件“D:\web_proyects\stickers-gallito-app\shop\management\commands\categories.py”,第 23 行,在 for row in tmp_data_categories.iterrows() TypeError: tuple indices must be integers or slices, not str
我在想是因为我如何制定我的 for 循环来读取数据。
模型.py:
class Category(models.Model):
category = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
image = models.ImageField(upload_to='category', blank=True, null=True)
video = EmbedVideoField(null=True, blank=True)
class Meta:
ordering = ('category',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_url(self):
return reverse('shop:allCat', args=[self.slug])
def __str__(self):
return '{}'.format(self.name)
命令/categories.py:
import pandas as pd
import csv
from shop.models import Category
from django.core.management.base import BaseCommand
tmp_data_categories=pd.read_csv('static/data/categories.csv',sep=',', encoding="utf-8")
class Command(BaseCommand):
def handle(self, **options):
categories = [
Category(
category=row['category'],
slug=row['product'],
subcategory=row['slug'],
subcategory_slug=row['description'],
description=row['size'],
image =row['quantity'],
video=row['image'],
)
for row in tmp_data_categories.iterrows()
]
Category.objects.bulk_create(categories)
调用时出现错误:
python manage.py categories
解决方案
这不起作用,因为 django 的models.py不是一个类似 dict 的对象。
但是,当你不需要的时候,你为什么在这里使用熊猫。见证:
tmp_data_categories=csv.DictReader('static/data/categories.csv', fieldnames=['category', 'product', 'slug', 'description', 'size', 'quantity', 'image'])
categories = [
Category(
category=row['category'],
slug=row['product'],
subcategory=row['slug'],
subcategory_slug=row['description'],
description=row['size'],
image =row['quantity'],
video=row['image'],
)
for row in tmp_data_categories
]
希望有帮助。
推荐阅读
- excel - VBA将线条颜色更改为与虚线相同
- json - How to avoid node_modules tests, e.g. json-schema-traverse?
- java - java SAXParser 忽略异常并继续解析
- javascript - 如何不从在线 csv 绘制不需要的信息
- javascript - Using vanilla JS to set image src from data-attribute
- xamarin - 如何在 xamarin 上使用自定义渲染器录制视频
- jquery - jQuery UI 和 nestedSortable 放在空列表上
- flutter - 在颤振中创建可重用的appBar
- c - C 是否更喜欢 C 函数实现中的 (void) arglist?
- groovy - 无法使用 CredentialInterceptor 测试 BaselinePipelineTest