我试图用来自外部CSV文件的数据填充Django SQL数据库,但是当我运行填充文件时,父ManyToManyField模型(Film)将不接受我从子对象(演员)提供的查询对象模型,因为(我认为)这是一个列表。是否可以使用get_or_create调用将列表解析为模型?如果没有,我该如何解决此问题?
我的models.py文件如下:
class Actor(models.Model):
actor_id = models.CharField(max_length=20, unique=True)
name = models.CharField(max_length=40)
class Film(models.Model):
film_id = models.CharField(max_length=20, unique=True)
title = models.CharField(max_length=60)
actors = models.ManyToManyField(Actor)
我的populate.py文件如下所示:
import pandas
df = read_csv('csv_file.csv')
def populate_film():
for index, row in in df.iterrows():
film_csv_id = str(row['IMDb ID'])
film_name = str(row['Film'])
list_of_actors = row['Actors']
#The CSV actors column returns a the list of actor_ids which I query against the Actor model
#I then put these queries into a list for the get_or_create step
actor_query_list = []
for actor_csv_id in list_of_actors:
actor_query = Actor.objects.get(actor_id = actor_csv_id)
actor_query_list.append(actor_query.id)
film = Film.objects.get_or_create(film_id = film_csv_id, title = film_name, actors = actor_query_list)
我收到的错误消息为:
Field 'id' expected a number but got [xxxx, xxxx].
谢谢!
答案 0 :(得分:0)
如果要将字段用作ID而不是默认ID字段,则应将“ primary_key”属性设置为True,如下所示:
actor_id = models.CharField(max_length=20, primary_key=True)
可能会解决您的问题