如何使用带有枚举列的SQLAlchemy插入多对多关系数据?

时间:2019-03-12 10:21:50

标签: python mysql flask sqlalchemy flask-sqlalchemy

我将烧瓶与SQLAlchemy一起使用,有一个User类与Role有多对多的关系。角色具有一个名称属性,该属性是一个枚举(RoleType)。

当我尝试使用默认用户角色插入新用户时:

        with client.session() as session:

            r = session.query(Role).filter(RoleType.USER.name == Role.name).first()
            user.roles = [r]

            session.add(user)
            session.commit()

我收到以下异常:

'RoleType' object has no attribute 'translate'

以下是User,Role和RoleType类:

from sqlalchemy import ForeignKey, Column, String, Integer, Boolean, Table
from sqlalchemy.orm import relationship, backref

user_role_association_table = Table('user_role', BaseRelation.metadata,
                                Column('user_id', Integer, ForeignKey('user.id')),
                                Column('role_name', Integer, ForeignKey('role.name')))


class User(BaseRelation):
    id = Column(String, primary_key=True, nullable=False)
    email = Column(String, nullable=False)
    password = Column(String, nullable=False)
    active = Column(Boolean, default=False, nullable=False)
    roles = relationship(Role,
                     lazy='subquery',
                     secondary=user_role_association_table)

from enum import auto, Enum

class Role(BaseRelation):
    name = Column(Enum(RoleType), primary_key=True)

    def __init__(self, **kwargs):
        name = kwargs.get("name", None)
        if (name is not None) and isinstance(name, str):
            kwargs["name"] = RoleType.get_type(name)

        super(Role, self).__init__(**kwargs)

    def __eq__(self, other):
        if isinstance(other, dict):
            return self.name == other.get('name', None)

        return self.name == other.name

    def __hash__(self):
        return hash(self.name)

    def __json__(self):
        return ['name']

class RoleType(Enum):
    USER = auto()
    ADMIN = auto()

0 个答案:

没有答案