【问题标题】:django-import-export: How to import data with foreign keys that doesn't have the keys, but the names?django-import-export:如何使用没有键但名称的外键导入数据?
【发布时间】:2015-09-08 20:33:08
【问题描述】:

我正在尝试设置 django-import-export 来处理存储在电子表格中的数据。 电子表格不包含作为 ID 的外键,而是包含相关对象的(也是唯一的)名称。 在我的数据库中,我将拥有Teachers 的外键关系,他们在Schools 工作,位于Cities

想象一下这是模型(摘录):

class School(models.Model):
    city = models.ForeignKey(City)
    name = models.CharField(max_length=200)


class Teacher(models.Model):
    school = models.ForeignKey(School)
    name = models.CharField(max_length=200)

教师的电子表格可能如下所示:

school,name
Central Grammar School,John Smith
West Primary,Jane Doe
West Primary,John Doe
...,...

如何构建 SchoolResource 模型,以便在导入期间它接受名称而不是 ID?

(我不能只从数据库中获取 ID,因为在某一时刻,我的想法是仅使用不包含任何 ID 的电子表格数据从头开始创建数据库。)

【问题讨论】:

    标签: python django foreign-keys relationships django-import-export


    【解决方案1】:

    ForeignKeyWidget 接受可选的field 参数,因此在SchoolResource 中看起来像这样:

    school = fields.Field(column_name='school',
                          attribute='school', 
                          widget=ForeignKeyWidget(School, 'name'))
    

    请参阅ForeignKeyWidget 的文档。

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      相关资源
      最近更新 更多