使用外键时SQLAlchemy中的映射错误

时间:2019-04-26 13:55:21

标签: python mysql python-3.x sqlalchemy

我有两个SQLAlchemy模型,其中一个由主键引用。

这是我的父模型:

try:
    from sqlalchemy import Column, Integer, Enum, DateTime, String, ForeignKey
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm  import scoped_session, sessionmaker, relationship
    from sqlalchemy.orm import validates, backref
    import datetime
    from lib.dbConnector import Session
    from werkzeug.security import generate_password_hash
except ImportError as err:
    raise err

Base = declarative_base()

class users_table(Base):
    __tablename__ = 'users_table'
    userid = Column(String(50), unique= True, primary_key= True, nullable= False)
    username = Column(String(500), unique= True, nullable= False)
    password = Column(String(500), nullable= False)
    email = Column(String(500), nullable= False, unique= True)
    role = Column(String(10), default= 'user', nullable= False)
    created_on = Column(DateTime, nullable= False, default= datetime.datetime.utcnow)
    updated_on = Column(DateTime, nullable= False, default= datetime.datetime.utcnow)

这是我的子表:

try:
    from sqlalchemy import Column, Integer, Enum, DateTime, String, ForeignKey
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm  import scoped_session, sessionmaker, relationship
    from sqlalchemy.orm import validates
    import datetime
    from lib.dbConnector import Session
except ImportError as err:
    raise err

Base = declarative_base()

class user_status_table(Base):
    __tablename__ = 'user_status_table'
    id = Column(Integer, primary_key= True, nullable= False, unique= True, autoincrement=True)
    userid = Column(String(50), ForeignKey('models.usersModel.users_table.userid'), nullable= False, unique= True)
    status = Column(String(50), default= 'active', nullable= False)
    updated_on = Column(DateTime, nullable= False, default= datetime.datetime.utcnow)
    userid = relationship('models.usersModel.users_table.users_table', foreign_keys=userid)

在运行服务器时,出现以下错误

"One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|user_status_table|user_status_table'. Original exception was: mapper"

有人可以建议我在这里做错什么吗? 这是我进行转换的地方

userdata = usersModel.users_table(userid, username, password, email, role)
            try:
                self.session.add(userdata)
                self.session.flush()
                userstatusdata = userstatusModel.user_status_table(userdata.userid, 'active')
                self.session.add(userstatusdata)
                self.session.commit()
            except:
                self.session.rollback()
                raise 

1 个答案:

答案 0 :(得分:0)

在回答您的问题之前,有几点评论:

  1. 请勿在导入周围进行try / except,然后在except子句中加注。这只会使您的回溯更加复杂
  2. 您的导入以及表定义包含许多对您的问题无关紧要的代码。不要那样做。

我用代码创建了两个文件,将它们清理掉以删除我确定不需要的东西。 usermodel.py包含以下内容:

from sqlalchemy import Column, Integer, Enum, DateTime, String, ForeignKey
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class users_table(Base):
    __tablename__ = 'users_table'
    userid = Column(String(50), unique= True, primary_key= True, nullable= False)
    username = Column(String(500), unique= True, nullable= False)

userstatus.py包含:

from usermodel import Base, users_table
from sqlalchemy import Column, Integer, Enum, DateTime, String, ForeignKey
from sqlalchemy.orm  import relationship

class user_status_table(Base):
    __tablename__ = 'user_status_table'
    id = Column(Integer, primary_key= True, nullable= False, unique= True, autoincrement=True)
    userid = Column(String(50), ForeignKey('users_table.userid'), nullable= False, unique= True)
    user = relationship('users_table')

突出显示了一些更改:

  • 我删除了第二个Base变量的创建,并将该变量导入到userstatus.py中,因此两个表都在同一模式中。我认为您不需要导入用户模型,但是我没有检查
  • SQLAlchemy从__tablename__属性中识别表。不能以类名作为前缀。

让我们测试一下

Python 3.6.5 (default, Mar 31 2018, 19:45:04) [GCC] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import usermodel
>>> import userstatus
>>> usr1 = usermodel.users_table(userid='You', username='Zacharia')
>>> stat1 = userstatus.user_status_table(id=1, user=usr1)
>>> stat1.user
<usermodel.users_table object at 0x7fa2ddbabfd0>
>>> stat1.user.userid
'You'