2

I'm using flask with SQLAlchemy, there is a User class with a many-to-many relation to Role. Role has a name property which is an enum (RoleType).

When I try to insert a new user with a default User role:

        with client.session() as session:

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

            session.add(user)
            session.commit()

I get the following exception:

'RoleType' object has no attribute 'translate'

Here are the User, Role and RoleType classes:

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()
3
  • could you post the entire code of is used to create your models including the imports Commented Mar 12, 2019 at 10:54
  • I've added some imports, Additionally - BaseRelation is an internal class which forces created_time & updated_time on all models. Commented Mar 12, 2019 at 11:28
  • I hope this helps Commented Mar 12, 2019 at 17:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.