Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change model representation in Flask-Admin without modifying model

I have a model with a __repr__ method, which is used for display in Flask-Admin. I want to display a different value, but don't want to change the model. I found this answer, but that still requires modifying the model. How can I specify a separate representation for Flask-Admin?

class MyModel(db.Model):
    data = db.Column(db.Integer)

    def __repr__(self):
        return '<MyModel: data=%s>' % self.data

Update

File: models.py

class Parent(db.Model):
    __tablename__ = "parent"
    id = db.Column(db.Integer, primary_key=True)
    p_name = db.Column(db.Text)
    children = db.relationship('Child', backref='child', lazy='dynamic')

    def __repr__(self):
        return '<Parent: name=%s' % self.p_name


class Child(db.Model):
    __tablename__ = "child"
    id = db.Column(db.Integer, primary_key=True)
    c_name = db.Column(db.Text)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'))

File: admin.py

from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView
from app import app, db
from models import Parent, Child


admin = Admin(app, 'My App')

admin.add_view(ModelView(Parent, db.session))
admin.add_view(ModelView(Child, db.session))

When I try to create or edit "child" through admin panel, I see representation from "Parent" class. I suppose it is because of relationship and I don't know how to redefine the representation for admin panel only.

like image 808
peoff Avatar asked May 04 '16 14:05

peoff


1 Answers

The following answers have helped me to solve my issue:

  • How to tell flask-admin to use alternative representation when displaying Foreign Key Fields?
  • Flask-admin, editing relationship giving me object representation of Foreign Key object
  • Flask-Admin Many-to-Many field display

The cause was in that I tried to replace __repr__ with __unicode__ instead just add __unicode__ method.

But if anybody knows solution without modifying models, let me know and I'll add it here.

like image 125
peoff Avatar answered Nov 15 '22 05:11

peoff