如何使用.csv文件填充Django中的ManyToMany字段? [英] How to populate a ManyToMany Field in Django using a .csv file?
问题描述
我有2个模型影响者和类别.Impactr与Category有很多关系.模型如下:
I have 2 models Influencer and Category. Influencer has a many to many relationship with Category.The models look like this:
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
和
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)
我编写了一个python脚本,用于解析csv文件并将数据发送到PostgreSQL数据库.
I have written a python script that parses a csv file and sends the data to a PostgreSQL database.
在csv文件中,类别列以数组的形式出现,如下面给出的
In the csv file the column Category is present as an array, like the one given below
[食物",酒吧",酒吧",学生",学生",化妆",化妆",印度",印度"]
csv文件的屏幕截图
A screenshot of the csv file
当我在python中打印列Category的类型时,它显示为字符串.我编写的用于解析并将数据发送到数据库的函数如下.我现在从该函数中排除了category选项.
When I print the type of column Category in python it shows it as a string. 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.
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.
除了使用ManyToManyField之外,还有其他选择吗?我尝试了django-multiselected字段,但效果不佳.
Are there any other alternatives other than using a ManyToManyField? I have tried django-multiselected field but it doesn't work well.
推荐答案
这应该可以解决问题:
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)
我假设在类别"列中看到的格式与您粘贴的代码段一致(使用单引号和 []
表示列表).在这种情况下,可以使用 ast
模块将该列直接解析为python文字,即字符串列表;)
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 ;)
这篇关于如何使用.csv文件填充Django中的ManyToMany字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!