Django导出Excel时外键显示PK而非名称及DateTime字段报错问题
问题1:导出Excel时外键字段显示PK而非名称
解决方案分两种常见场景:
场景1:使用django-import-export库导出
如果用django-import-export的ModelResource,需要给外键字段指定ForeignKeyWidget来关联显示名称字段:
from import_export import fields, resources from import_export.widgets import ForeignKeyWidget from .models import YourModel, User # 替换为你的业务模型和关联模型 class YourModelResource(resources.ModelResource): # 自定义外键字段,显示关联对象的名称(比如username或name,根据你的模型字段调整) assignee = fields.Field( column_name='经办人', # Excel列名可自定义 attribute='assignee', widget=ForeignKeyWidget(User, 'username') ) author = fields.Field( column_name='创建人', attribute='author', widget=ForeignKeyWidget(User, 'username') ) class Meta: model = YourModel fields = ('id', 'assignee', 'author', ...) # 补充其他需要导出的字段
场景2:手动生成Excel(如openpyxl、xlwt)
遍历查询集时,直接访问外键对象的名称字段,而非取PK值:
from openpyxl import Workbook from .models import YourModel wb = Workbook() ws = wb.active ws.append(['ID', '经办人', '创建人']) # 写入表头 for obj in YourModel.objects.all(): # 处理外键为空的情况,避免报错 assignee_name = obj.assignee.name if obj.assignee else '无' author_name = obj.author.username if obj.author else '无' ws.append([obj.id, assignee_name, author_name]) wb.save('export.xlsx')
问题2:添加created_at/updated_at时出现“Cannot resolve keyword 'created at' into field”错误
这个错误是字段名书写错误导致的:Django模型里定义的字段是created_at(下划线分隔),但你在查询或导出配置里写成了created at(空格分隔)。
解决步骤:
- 确认模型字段定义正确:
from django.db import models class YourModel(models.Model): # 其他业务字段 created_at = models.DateTimeField(auto_now_add=True) # 自动记录创建时间 updated_at = models.DateTimeField(auto_now=True) # 自动记录更新时间
- 检查所有用到该字段的代码,把
created at替换为created_at:- 查询语句示例:
YourModel.objects.filter(created_at__gte=start_date) - 导出配置示例(django-import-export):
fields = ('created_at', 'updated_at')
- 查询语句示例:
内容的提问来源于stack exchange,提问作者Victor Calimano
相关产品推荐
相关产品推荐

