Change model representation in Flask-Admin without modifying model
Asked Answered
Q

3

6

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.

Quittor answered 4/5, 2016 at 14:57 Comment(0)
Q
1

The following answers have helped me to solve my issue:

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.

Quittor answered 5/5, 2016 at 13:39 Comment(0)
N
0

You could subclass the model:

class MyNewModel(MyModel):
    def __repr__(self):
        return '<MyModel: DATA IS %d!>' % self.data

and then use MyNewModel instead of MyModel.

Notable answered 4/5, 2016 at 15:34 Comment(1)
It was my first idea to make like this, but it doesn't work in my case, please see an update.Quittor
M
0

I have the same problem and I've found this solve:

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

setattr(Parent, '__repr__', Child.__repr__)

It overloads Parent.__repr__, but now you can not to change SQLA model.

Menam answered 3/12, 2022 at 18:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.