对于Django模型我使用django-import-export包。
手册说我可以导出目标模型中不存在的字段,如下所示:
from import_export import fields
class BookResource(resources.ModelResource):
myfield = fields.Field(column_name='myfield')
class Meta:
model = Book
http://django-import-export.readthedocs.org/en/latest/getting_started.html
如何从模型中导出函数输出?例如Book.firstword()
答案 0 :(得分:6)
以下是您应该如何做的(请查看https://django-import-export.readthedocs.org/en/latest/getting_started.html#advanced-data-manipulation):
from import_export import fields, resources class BookResource(resources.ModelResource): firstword = fields.Field() def dehydrate_firstword(self, book): return book.firstword() class Meta: model = Book
更新以回答OP评论
要按特定顺序返回字段,您可以使用export_order
Meta选项(https://django-import-export.readthedocs.org/en/latest/api_resources.html?highlight=export_order#import_export.resources.ResourceOptions)。
答案 1 :(得分:1)
还有一个解决方案,代码少于Serafeim建议的代码:
from import_export import fields, resources
class BookResource(resources.ModelResource):
firstword = fields.Field(attribute='firstword')
class Meta:
model = Book
答案 2 :(得分:0)
以防万一您需要获取该字段的完整 URL 并基于@Serafeim 的解决方案
class CompanyModelResource(ModelResource):
def dehydrate_local_logo(self, company):
if company.local_logo and hasattr(company.local_logo, 'url'):
return company.local_logo.url
return company.local_logo
class Meta:
model = Company