首页 > 解决方案 > 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

标签: pythondjangopandas

解决方案


这不起作用,因为 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
        ]

希望有帮助。


推荐阅读