首页 > 解决方案 > 使用 django-import-export 通过 url 将外键 id 传递给导入的 csv 文件

问题描述

我正在尝试使用 django-import-export 将一些数据从 csv 文件导入 django 数据库,并带有外键(位置)。我想要实现的是,location_id 是由请求 url 传递的。

value,datetime,location
4.46,2020-01-01,1
4.46,2020-01-02,1

我的网址看起来像这样,所以我希望将“location_id”传递到上传的 csv 文件中:

urlpatterns = [
...
...
    path('..../<int:location_id>/upload', views.simple_upload, name='upload'),
   ]

我的观点是这样的:

def simple_upload(request, location_id):
    if request.method == 'POST':

        rainfall_resource = RainfallResource()
        dataset = Dataset()
        new_rainfall = request.FILES['myfile']


        imported_data = dataset.load(new_rainfall.read().decode("utf-8"), format="csv")


        try:
            result = rainfall_resource.import_data(dataset, dry_run=True)  # Test the data import
        except Exception as e:
            return HttpResponse(e, status=status.HTTP_400_BAD_REQUEST)

        if not result.has_errors():
            rainfall_resource.import_data(dataset, dry_run=False)  # Actually import now


       return render(request, '/import.html')

我的 ModelResource 看起来像这样:

class RainfallResource(resources.ModelResource):

    location_id = fields.Field(
        column_name='location_id',
        attribute='location_id',
        widget=ForeignKeyWidget(Location, 'Location'))

    class Meta:
        model = Rainfall

    def before_import_row(self, row, **kwargs):
        row['location'] = location_id

当我硬编码“location_id”时,操作有效,例如:

    def before_import_row(self, row, **kwargs):
        row['location'] = 123

但是,我不明白如何将 location_id 参数从“url”传递给“before_import_row”函数。帮助将不胜感激:-)

标签: pythonkeyword-argumentdjango-import-export

解决方案


我认为你必须imported_data在导入之前修改你的内存。

您可以使用tablib API来更新数据集:

# import the data as per your existing code
imported_data = dataset.load(new_rainfall.read().decode("utf-8"), format="csv")

# create an array containing the location_id
location_arr = [location_id] * len(imported_data)

# use the tablib API to add a new column, and insert the location array values
imported_data.append_col(location_arr, header="location")

通过使用这种方法,您不需要覆盖before_import_row()


推荐阅读