Model.py
class Tag(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.name
class Question(models.Model):
name = models.CharField(max_length=255, unique=True)
Tag_name = models.ManyToManyField(Tag)
我需要创建一个API,以将csv中的数据加载到表中。
全部取决于您的CSV格式。由于模型中包含多对多字段,因此应定义CSV,以便可以根据需要添加任意数量的“多到多字段”。假设您的CSV具有以下格式。
name | type
Question 1 | question
Tag 11 | tag
Tag 12 | tag
Tag 13 | tag
Question 2 | question
Tag 21 | tag
Tag 22 | tag
Tag 23 | tag
Tag 24 | tag
对于这种类型的格式,您可以这样编写代码
csv_rows = # write code to get CSV rows here
q_obj = None
for row in csv_rows:
if row[1] == 'question':
q_obj = Question.objects.create(name=row[0])
elif row[1] == 'tag':
if q_obj:
tag_obj = Tag.objects.create(name=row[0])
q_obj.Tag_name.add(tag_obj)
此格式和代码将处理任何数量的问题标签