使用django-import-export通过URL将外键ID传递到导入的csv文件中

问题描述 投票:0回答:1

我正在尝试使用带有外键(位置)的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”函数。帮助将不胜感激:-)

python kwargs import-csv django-import-export
1个回答
0
投票

我认为您必须在导入之前修改内存中的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()

© www.soinside.com 2019 - 2024. All rights reserved.