如何通过SQLAlchemy从多对多表中选择列

时间:2018-01-23 11:21:33

标签: python sqlalchemy

roles_users = db.Table('roles_users',
    db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
    db.Column('role_id', db.Integer(), db.ForeignKey('role.id')),
    db.Column('created_at', db.DateTime())

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

class User(db.Model, UserMixin):
    id = db.Column(db.Integer(), primary_key=True)
    email = db.Column(db.String(255), nullable=False, unique=True)
    roles = db.relationship('Role', secondary=roles_users,
                        backref=db.backref('users', lazy='dynamic'))

我想通过&created; created_at'来获得用户的角色。多对多表中的列。

预期结果:

[
    {user_id:1, role:'user', created_at:dateTime},
    {user_id:1, role:'admin', created_at:dateTime}
]

0 个答案:

没有答案