How to export column with relations in flask-admin

I have a problem exporting to csv tables, whose relationship with others, while in "simple" work it is good. Should I add some basics 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 is ModelView

class CategorieAdmin(sqla.ModelView):
    column_display_pk = True
    can_export = True
    export_types = ['xls']
    list_columns = ['categoria', 'tipo']

      

Error generation: Exception: Unexpected data type <class '__main__.Tipo'>

thanks for the help

+3


source to share


1 answer


The question is quite old, but I had the same problem and resolved it with column_formatters_export .

column_formatters_export is an attribute that can be assigned to a dictionary where keys are the names of the columns in the model and their values ​​are assigned to a function that adds functionality to change the format or whatever 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 a model and you can get any column in your model. Another possible solution is to add a view 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)
      )

      

+3


source







All Articles