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

Passing foreign key id via url to imported csv file using django-import-export

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

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

我的 url 看起来像这样,所以我希望 "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')

我的模型资源如下所示:

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" 函数。非常感谢您的帮助:-)

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