【问题标题】:Send csv file data to sqlite table in django将csv文件数据发送到django中的sqlite表
【发布时间】:2020-02-17 12:46:57
【问题描述】:

模型.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 中的数据载入表格。

【问题讨论】:

    标签: django django-models django-rest-framework django-forms django-views


    【解决方案1】:

    这完全取决于您的 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)
    

    这种格式和代码可以处理任意数量的问题标签

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 2010-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多