I have two SQLAlchemy models, which one is referred by primary key.

This is my parent model:

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)

and this is my child table:

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)

While running my server I am getting the following error

"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"

Can anyone suggest what am I doing wrong here? And this is where I commit the transction

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 Answers

0
Menno Hölscher On Best Solutions

Before we go into answering your question, there are a few remarks:

  1. Don't do a try/except around imports and then just raise in the except clause. It just makes your tracebacks more complicated
  2. Your imports as well as the table definitions contain a lot of code that is immaterial to your question. Do not do that.

I created two files with the code, cleaned up to remove things I was sure not to need. The usermodel.py contain the following:

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)

The userstatus.py contains:

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')

Some of the changes highlighted:

  • I removed the creation of the second Base variable, and imported the variable in userstatus.py, so both tables are in the same schema. I do not think you need to import usermodel, but I did not check
  • SQLAlchemy recognizes tables from the __tablename__ attribute. This must not be prefixed with the classname.

Let's test:

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'