【问题标题】:Django: import data from CSV - tuple indices must be integers or slices, not strDjango:从 CSV 导入数据 - 元组索引必须是整数或切片,而不是 str
【发布时间】:2019-08-31 00:20:37
【问题描述】:

在我的 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 循环来读取数据。

models.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)

commands/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

【问题讨论】:

    标签: python django pandas


    【解决方案1】:

    因为 iteritems 上的迭代返回一个无法使用字符串索引的元组。该元组的第二个元素是 pandas 系列,它可以使用字符串名称进行下标。所以你应该这样做

    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()
            ] 
    

    【讨论】:

      【解决方案2】:

      这不起作用,因为 django 的 models.py 不是类似字典的对象。

      但是,当你不需要的时候,你为什么在这里使用 pandas。证人:

      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
              ]
      

      希望对您有所帮助。

      【讨论】:

      • 得到:AttributeError: 'DictReader' object has no attribute 'iterrows'
      • 在使用 csv.DictReader 时,您知道如何将 CSV 中的空白替换为 " " 空格或 null 以被接受到数据库中吗?
      • 我认为这不可能轻易做到。不过,您可以添加另一个循环并自己执行。
      猜你喜欢
      • 2018-03-12
      • 2017-03-11
      • 2019-11-23
      • 2018-12-29
      • 1970-01-01
      • 2021-09-08
      • 2021-01-18
      • 2016-05-25
      • 1970-01-01
      相关资源
      最近更新 更多