python - 使用 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”函数。帮助将不胜感激:-)
解决方案
我认为你必须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()
推荐阅读
- javascript - Rails 中 React Native webview 重定向页面上的 postMessage
- python - 给定这个 aplhanumeric 数据集,如何在 python 中训练预测?
- android-studio - 未找到连接的设备;请连接设备,或查看 flutter.io/setup 以获取入门说明
- ios - Xcode 不断尝试使用我删除的帐户登录 Apple 开发者帐户
- opentbs - 如何不在 tbs:page 上复制段落
- selenium - 如何防止硒打开新的Firefox窗口?
- java - Java中的Lambda表达式返回类型
- html - 使用 div 样式的表格 - 表格单元格的宽度大于窗口大小(一行/不换行)
- java - 如何为 JsonObjects 的 JsonObject 创建 Jackson XML POJO 类
- javascript - 根据用户选择的值,将 20 个不同的静态值乘以 12,然后显示总数