Flask-Admin view with many to many relationship model

倖福魔咒の 提交于 2020-02-02 13:42:26

问题


I have this basic flask-admin set-up with users and user roles

class Role(db.Model, RoleMixin):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    active = db.Column(db.Boolean())
    confirmed_at = db.Column(db.DateTime())
    roles = db.relationship('Role', secondary="roles_users",
                            backref=db.backref('users', lazy='dynamic'))
class RolesUsers(db.Model):
    __tablename__="roles_users"
    id = db.Column(db.Integer(), primary_key=True)
    user_id = db.Column(db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE'))
    role_id = db.Column(db.Integer(), db.ForeignKey('role.id', ondelete='CASCADE'))

I want to display user view that will show roles specific user has. With one to many relationship I would do somethin like this

class UserView(ModelView):
    column_hide_backrefs = False

class Role(db.Model, RoleMixin):
    ...
    def __str__(self):
        return self.name

How would I do this with many to many relationship


回答1:


So it turns out that I only needed to add column_list property to UserView like this

class UserView(ModelView):
    column_hide_backrefs = False
    column_list = ('email', 'active', 'roles')

the rest is handled by flask-admin



来源:https://stackoverflow.com/questions/46452927/flask-admin-view-with-many-to-many-relationship-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!