【问题标题】:sqlalchemy ---》type object 'role_user' has no attribute 'foreign_keys'sqlalchemy ---》类型对象'role_user'没有属性'foreign_keys'
【发布时间】:2013-04-08 08:47:29
【问题描述】:
class User(Base):
    """
        users table
    """
    __tablename__ = 'users'

    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8'
    }

    id = Column(INTEGER, primary_key=True)
    email = Column(String(64), nullable=False, unique=True)
    password = Column(String(64), nullable=False)
    name = Column(String(32), nullable=False)
    last_login_time = Column(DateTime, default='')
    last_login_ip = Column(String(32), default='')
    create_time = Column(DateTime, nullable=False)
    status  = Column(SMALLINT, default=0)
    role = relationship("Role",
                    secondary="role_user",
                    backref=backref('user'))

    def __init__(self, email, password, name, last_login_time=now,
                            last_login_ip='0', create_time=now, status=0):
        self.email = email
        self.password = md5(password)
        self.name = name
        self.last_login_time = last_login_time
        self.last_login_ip = last_login_ip
        self.create_time = create_time
        self.status = status

    def __repr__(self):
        return "<User('%s', '%s')>" % (self.name, self.email)

class Role(Base):
    """
        roles table
    """
    __tablename__ = 'roles'

    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8'
    }

    id = Column(SMALLINT(5), primary_key=True)
    name = Column(String(32), nullable=False, unique=True)

    def  __init__(self, name):
        self.name = name

    def  __repr__(self):
        return "<Role('%s', '%s')>" % (self.id, self.name)


class role_user(Base):
    """
        role_user association table
    """

    __tablename__ = 'role_user'

    __table_args__ = {
        'mysql_engine': 'InnoDB',
        'mysql_charset': 'utf8'
    }

    user_id = Column(INTEGER, ForeignKey('users.id'), primary_key=True)
    role_id = Column(SMALLINT(5), ForeignKey('roles.id'), primary_key=True)

    def __init__(self, user_id, role_id):
        self.user_id = user_id
        self.role_id = role_id

当我创建一个用户时,我遇到了错误:

u1 = User(email='john@example.com', password='12345', name='john')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "<string>", line 2, in __init__
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/orm/instrumentation.py", line 310, in _new_state_if_none
    state = self._state_constructor(instance, self)
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/util/langhelpers.py", line 582, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/orm/instrumentation.py", line 145, in _state_constructor
    self.dispatch.first_init(self, self.class_)
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/event.py", line 409, in __call__
    fn(*args, **kw)
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/orm/mapper.py", line 2209, in _event_on_first_init
    configure_mappers()
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/orm/mapper.py", line 2118, in configure_mappers
    mapper._post_configure_properties()
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/orm/mapper.py", line 1242, in _post_configure_properties
    prop.init()
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/orm/interfaces.py", line 231, in init
    self.do_init()
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/orm/properties.py", line 1028, in do_init
    self._setup_join_conditions()
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/orm/properties.py", line 1102, in _setup_join_conditions
    can_be_synced_fn=self._columns_are_mapped
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/orm/relationships.py", line 114, in __init__
    self._determine_joins()
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/orm/relationships.py", line 180, in _determine_joins
    consider_as_foreign_keys=consider_as_foreign_keys
  File "/usr/local/lib/python2.6/dist-packages/SQLAlchemy-0.8.1dev-py2.6-linux-i686.egg/sqlalchemy/sql/util.py", line 345, in join_condition
    b.foreign_keys,
AttributeError: type object 'role_user' has no attribute 'foreign_keys'
>>> 
jiankong@ubuntu:~/git/admin-server$ python manage.py shell
Python 2.6.5 (r265:79063, Oct  1 2012, 22:07:21) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from apps.auth.models import User
>>> u1 = User(email='john@example.com', password='12345', name='john')

我能做些什么来解决这个问题?谢谢!!

【问题讨论】:

  • 在哪里?我不明白。

标签: sqlalchemy many-to-many


【解决方案1】:

role_user 的名称有冲突,因为有一个名为 role_user 的类和一个同名的表。所以secondary="role_user" 首先选择类对象。可以这样表述:

relationship("Role", secondary="role_user.__table__")

编辑:理想情况下,您将“role_user”定义为仅表,并在执行“辅助”之前定义它。按照http://docs.sqlalchemy.org/en/latest/orm/relationships.html#many-to-many 的示例进行操作。

【讨论】:

  • InvalidRequestError: 类 没有名为 'table' 的映射列 我收到另一个错误。
  • 更好的方法是避免硬编码,所以我更喜欢使用:secondary=lambda: ModelClass.__table__,在这种情况下它将是secondary=lambda: role_user.__table__
猜你喜欢
  • 1970-01-01
  • 2013-10-12
  • 1970-01-01
  • 2020-02-21
  • 2021-09-25
  • 1970-01-01
  • 2016-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多