简体   繁体   English

如何使用.csv文件填充Django中的ManyToMany字段?

[英]How to populate a ManyToMany Field in Django using a .csv file?

I have 2 models Influencer and Category. 我有2个模型影响者和类别。 Influencer has a many to many relationship with Category.The models look like this: 有影响者与Category有很多关系,模型如下所示:

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

    def __str__(self):
        return self.name

and

class Influencer(models.Model):
    full_name = models.CharField('Full Name',max_length=100)
    username = models.CharField('Username',max_length=100,unique=True)
    photo = models.ImageField(upload_to = 'photos/%Y/%m/%d/',blank=True)
    location_city = models.CharField('Location City',max_length=100,null=True,blank=True)
        categories = models.ManyToManyField(Category)

I have written a python script that parses a csv file and sends the data to a PostgreSQL database. 我已经编写了一个python脚本,用于解析csv文件并将数据发送到PostgreSQL数据库。

In the csv file the column Category is present as an array, like the one given below 在csv文件中,类别列以数组的形式出现,如下所示

['Food', 'Bar', 'Bar', 'Student', 'Student', 'makeup', 'makeup', 'India', 'India']

A screenshot of the csv file csv文件的屏幕截图 在此处输入图片说明

When I print the type of column Category in python it shows it as a string. 当我在python中打印列Category的类型时,它显示为字符串。 The function which I wrote to parse and send data to database is as follows.I have excluded the categories option from the function for now. 我编写的用于解析并将数据发送到数据库的函数如下。我现在从该函数中排除了category选项。

def write_to_db(file):
    with open(str(file),encoding='utf-8') as csvfile:
            csvreader = csv.reader(csvfile)
            next(csvreader,None)
            for row in csvreader:

                try:
                    if not Influencer.objects.filter(username = row[1]).exists() and check_email(row[2]):
                        _,created = Influencer.objects.get_or_create(
                                full_name = row[0],
                                username = row[1],
                                email_id = clean_email(row[2]),
                                external_url = row[8],


                                )

                except Exception as e:
                    print(e)

How should I write the code so that I can insert the categories in the many to many field with the respective Primary key of influencer. 我应该如何编写代码,以便可以使用影响者的主键在多对多字段中插入类别。

Are there any other alternatives other than using a ManyToManyField? 除了使用ManyToManyField以外,还有其他选择吗? I have tried django-multiselected field but it doesn't work well. 我尝试了django-multiselected字段,但效果不佳。

This should do the trick: 这应该可以解决问题:

import ast

def write_to_db(file):
    with open(str(file),encoding='utf-8') as csvfile:
        csvreader = csv.reader(csvfile)
        next(csvreader,None)
        for row in csvreader:
            try:
                if not check_email(row[2]):
                    continue
                influencer, _ = Influencer.objects.get_or_create(
                    full_name = row[0],
                    username = row[1],
                    email_id = clean_email(row[2]),
                    external_url = row[8],
                )
                categories_str = row[5]
                category_names = ast.literal_eval(categories_str)
                category_names = map(str.lower, category_names) # normalize them, all lowercase
                category_names = list(set(category_names)) # remove duplicates
                for category_name in category_names:
                    category, _ = Category.objects.get_or_create(name=category_name)
                    influencer.categories.add(category)
            except Exception as e:
                print(e)

I'm assuming the format I see there in the categories column is consistent with the snippet you pasted (using single quotes and [] to denote a list). 我假设我在类别列中看到的格式与您粘贴的代码段一致(使用单引号和[]表示列表)。 In that case the ast module can be used to parse this column directly into a python literal, a list of strings ;) 在这种情况下,可以使用ast模块将此列直接解析为python文字,字符串列表;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM