Search code examples
pythoncsvexportflask-admin

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


Solution

  • 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)
          )