目前有两种比较推荐的方法:
- 重写export方法在export方法中将表头及数据造出来,只需要将数据写入列表中即可,推荐使用sql,连表查询比较灵活,需要注意的是表头要和数据一一对应,不然报错:
class IncomingValuableGroupViewResource(resources.ModelResource):
class Meta:
model = IncomingValuableGroupView
# fields = ('id', 'author_name',)
def export(self, queryset=None, *args, **kwargs):
headers = ['序号', '日期', '清点SKU种类', '清点SKU数量', '质检SKU种类', '质检SKU数量', '加工SKU种类', '加工SKU数量', '上架SKU种类', '上架SKU数量',
'目的仓库']
data = tablib.Dataset(headers=headers)
from django.db import connection
cr = connection.cursor()
sql = """
select A.id,
A.create_date_without_time,
A.count_product_check,
A.sum_actual_check_qty,
A.count_product_quality,
A.sum_actual_quality_qty,
A.count_product_processing,
A.sum_actual_processing_qty,
A.count_product_shelves,
A.sum_actual_shelves_qty,
B.name as location_name
from incoming_valuable_group_view as A,
stock_location as B
where A.location_id = B.id;
"""
cr.execute(sql)
res = cr.fetchall()
for insert_data in res:
data.append(insert_data)
self.after_export(queryset, data, *args, **kwargs)
return data
- 我目前没有使用过,但也挺简单的,不需要重写
export
方法,直接在数据库中创建视图,并在项目中创建相应的模型,视图,按照常规的文件下载方式设置即可,这里比较麻烦的是需要重新创建模型,但是以后维护方便,以后加减字段,调整逻辑比较方便.
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/18446.html