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

China☆狼群 提交于 2021-01-20 12:47:09

问题


Im trying to import some data from a csv file to a django database using django-import-export, with a foreign key (location). What I want to achieve is, that the location_id is passed by the request url.

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

My urls look like this, so I want "location_id" to be passed into the uploaded csv file:

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

My view looks like this:

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')

My ModelResource looks like this:

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

The manipulation works when I hardcode "location_id" like:

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

However, I do not understand how to pass the location_id argument from the "url" to the "before_import_row" function. Help would be highly appreciated:-)


回答1:


I think you will have to modify your imported_data in memory, before importing.

You can use the tablib API to update the dataset:

# 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")

By using this approach, you won't need to override before_import_row()



来源:https://stackoverflow.com/questions/61675297/passing-foreign-key-id-via-url-to-imported-csv-file-using-django-import-export

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!