python - 我可以将具有多对一关系映射的 CSV 批量上传到 Django 吗?

标签 python django csv mapping

我正在尝试查找/创建一个允许将数据批量上传到 Django 的模块。我试图将许多艺术家与给定的节日联系起来,但到目前为止我发现的所有模块仅支持 1:1 上传。 https://github.com/edcrewe/django-csvimport

最佳答案

这是您想要执行的操作的示例。我已经删除了原始代码,因为它太大了。但这仍然会给您一个很好的起点。

实际上,客户端上传的 CSV 文件并不像我在示例中所示的那么简单。有些行是空白的,有些行包含一些其他不必要的信息,例如生成文件的软件名称、商店名称等。因此,我必须编写更多方法来过滤掉这些数据。但下面我还没有这样做。我尽可能减少示例。

from django.db import models
import csv


class Category(models.Model):
    name = models.CharField(max_length=10)


class Product(models.Model):
    category = models.ForeignKey(Category)
    uid = models.CharField(max_length=4)
    name = models.CharField(max_length=10)
    price = models.IntegerField()
    qty = models.IntegerField() # quantity


class CSVFile(models.Model):
    """
    This model allows for uploading a CSV file and then 
    updates data in Category and Product models
    """
    csv_file = models.FileField(upload_to='csvfiles')
    # feel free to add other fields like upload date, etc.

    def save(self, *args, **kwargs):
        """
        This is where you analyze the CSV file and update 
        Category and Product models' data
        """
        super(CSVFile, self).save(*args, **kwargs)
        self.csv_file.open(mode='rb')
        f = csv.reader(self.csv_file)
        for row in f:
            # currently the row is a list of all fields in CSV file
            # change it to a dict for ease
            row_dict = self.row_to_dict(row) # this method is defined below
            # check if product exists in db
            product = self.product_is_in_db(row_dict['uid']) # this method is defined below
            if product:
                # product is in db
                # update fields values
                self.update_product(product, row_dict) # this method is defined below
            else:
                # product is not in db
                # create this product
                self.create_product(row_dict) # this method is defined below

        self.csv_file.close()


    def row_to_dict(self, row):
        """Returns the given row in a dict format"""
        # Here's how the row list looks like:
        # ['category', 'product name', 'product uid' 'price', 'qty']
        return {'category': row[0], 'name': row[1], 
            'uid': row[2], 'price': row[3], 'qty': row[4]
            }

    def product_is_in_db(self, uid):
        """Check the product is in db. 
        If yes, return the product, else return None
        """
        try:
            return Product.objects.get(uid=uid)
        except Product.DoesNotExist:
            return None

    def update_product(self, product, row_dict):
        """Update the given product with new data in row_dict"""
        product.price = row_dict['price']
        product.qty = row_dict['qty']
        product.save()

    def create_product(self, row_dict):
        # First see, if category exists
        # If not, create a new category
        try:
            category = Category.objects.get(row_dict['category'])
        except Category.DoesNotExist:
            category = Category.objects.create(name=row_dict['category'])

        # Now, create the product
        Product.objects.create(
            name=row_dict['name'],
            uid=row_dict['uid'],
            price=row_dict['price'],
            qty=row_dict['qty'],
            category=category,
        )

关于python - 我可以将具有多对一关系映射的 CSV 批量上传到 Django 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38150971/

相关文章:

python - 鳕鱼和 python

python - 用python调用命令exe

python - Django REST Framework 中的序列化程序验证顺序

python - 如何在 django 中确定以前的 URL

javascript - Angular将csv文件上传到范围内而不发布到服务器

python - 如何在 ppt 中嵌入 python 图表(或图像)并刷新它

python - 如何复制 python bytearray 缓冲区?

python - 在 Python 中使用空字典创建一个集合返回 False

python - 使用 TensorFlow 的训练和预测出了什么问题?

excel - 有没有办法在 Mac 上使用 VBscript 代码将 CSV 转换为 XLS?