【问题标题】:Passing foreign key id via url to imported csv file using django-import-export使用 django-import-export 通过 url 将外键 id 传递给导入的 csv 文件
【发布时间】:2020-05-08 08:42:33
【问题描述】:

我正在尝试使用 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 keyword-argument django-import-export


    【解决方案1】:

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

    【讨论】:

    • 谢谢你,马修!完美!
    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多