问题
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