how to export column with relationship in flask-admin
Asked Answered
M

1

6

I have a problem in the export to csv the tables whose relationship with others, while in the 'simple' work well. I have to add some basis for export? For example, this is 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

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'>

Thanks for help

Montano answered 7/4, 2017 at 7:9 Comment(4)
How are you exporting the csv?Silici
when set can_export to true and add import tablib, appears the Export button, which creates the xls fileMontano
Maybe replace tipo here: list_columns = ['categoria', 'tipo'] with tipo_idSilici
if I replace 'tipo_id', the export works, but appear in the table numbers of tipo_id and not the corresponding 'tipo' that I need to be displayed and saved in .xlsMontano
D
4

The question is quite old but I had the same problem and I resolved it with 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.

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. 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)
      )
Daggett answered 14/9, 2017 at 10:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.