[英]how to export column with relationship in flask-admin
I have a problem in the export to csv the tables whose relationship with others, while in the 'simple' work well. 我在向csv导出与其他人关系的表时遇到问题,而在'简单'工作中则很好。 I have to add some basis for export?
我要为出口添加一些基础吗? For example, this is db.Model:
例如,这是db.Model:
class Categoria(db.Model):
__tablename__ = 'categorie'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
categoria = db.Column(db.String(30), primary_key=True)
tipo_id = db.Column(db.Integer, db.ForeignKey('tipi.id'), primary_key=True)
tipo = db.relationship('Tipo', backref='categorie')
and this the ModelView 这就是ModelView
class CategorieAdmin(sqla.ModelView):
column_display_pk = True
can_export = True
export_types = ['xls']
list_columns = ['categoria', 'tipo']
The error generate is: Exception: Unexpected data type <class '__main__.Tipo'>
生成的错误是:
Exception: Unexpected data type <class '__main__.Tipo'>
Thanks for help 感谢帮助
The question is quite old but I had the same problem and I resolved it with column_formatters_export . 这个问题已经很老了,但我遇到了同样的问题,我用column_formatters_export解决了这个问题。
column_formatters_export is an attribute that can be assigned to a dictionary where the keys are the name of the columns of the model, and their values are assigned to a function that adds functionality to change format or what you need. column_formatters_export是一个可以分配给字典的属性,其中键是模型列的名称,它们的值被分配给一个函数,该函数添加了更改格式或所需内容的功能。
For example for your code: 例如,对于您的代码:
class CategorieAdmin(sqla.ModelView):
column_display_pk = True
can_export = True
export_types = ['xls']
list_columns = ['categoria', 'tipo']
column_formatters_export = dict(
categoria=lambda v, c, m, p: '' if m.tipo is None else m.tipo.categoria
)
In m you have the model and you can get any column of your model. 在m你有模型,你可以得到你的模型的任何列。 Other possible solution is to add the representation method to your model.
其他可能的解决方案是将表示方法添加到模型中。
For example: 例如:
class Categoria(db.Model):
__tablename__ = 'categorie'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
categoria = db.Column(db.String(30), primary_key=True)
tipo_id = db.Column(db.Integer, db.ForeignKey('tipi.id'), primary_key=True)
tipo = db.relationship('Tipo', backref='categorie')
def __repr__(self):
return '%s' % self.categoria
class CategorieAdmin(sqla.ModelView):
column_display_pk = True
can_export = True
export_types = ['xls']
list_columns = ['categoria', 'tipo']
column_formatters_export = dict(
categoria=lambda v, c, m, p: '' if m.tipo is None else str(m.tipo)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.