【问题标题】:Import data containing title instead of ID in django在 Django 中导入包含标题而不是 ID 的数据
【发布时间】:2023-01-26 18:21:59
【问题描述】:

我正在使用 django 导入导出。它是一个扩展,用于使用 csv 文件将数据表导入管理面板。我有一个带有外键的模型:ProductModel,现在如果我想导入数据,我必须在 csv 中提供 ProductModel 的 ID。我想要绕过,所以我可以在 csv 中使用对象的标题而不是 id

class Item(models.Model):
    title = models.CharField(max_length=100)
    model = models.ForeignKey(ProductModel, ....)

class ProductModel(models.Model):
    title = models.CharField(max_length=100)
    desc = models.Tex.....

【问题讨论】:

    标签: python django django-models django-import-export


    【解决方案1】:

    您必须在 ForeignKeyWidget 定义中将“标题”声明为查找字段。

    例如:

    from import_export import fields, resources
    from import_export.widgets import ForeignKeyWidget
    
    class ItemResource(resources.ModelResource):
        model = fields.Field(
            column_name='model',
            attribute='model',
            widget=ForeignKeyWidget(ProductModel, 'title'))
    
        class Meta:
            fields = ('model',)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 2014-05-16
      • 1970-01-01
      • 2016-07-03
      相关资源
      最近更新 更多