一.sqlalchemy.cimmutabledict.immutabledict' object has no attribute 'setdefault'
环境版本: SQLAlchemy = 1.4.42 ,Flask-SQLAlchemy = 2.4.4 python = 3.7
issue git-hub: https://github.com/pallets-eco/flask-sqlalchemy/issues/928
解决:
通过降低SQLAlchemy 版本为1.3
二. 一对多关系映射时找不到User 类问题 sqlalchemy.exc.InvalidRequestError: When initializing mapper mapped class Address->address, expression 'Users' failed to locate a name ('Users'). If this is a class name, consider adding this relationship() to the <class 'autotest.dbs.test.tables.Address'> class after both dependent classes have been defined.
一个User 对应多个Address,一个地址属于其中一个用户,在进行orm 映射时配置如下:
Base1 = declarative_base()
class Address(Base1):
__tablename__ = 'address'
id = Column(Integer, primary_key=True)
email = Column(String, nullable=False)
user_id = Column(Integer,ForeignKey('user_account.id')) # 引用
user = relationship("Users", back_populates="address") #
def __repr__(self):
return f"Address(id={self.id!r}, email_address={self.email!r})"
Base2 = declarative_base()
class Users(Base2):
__tablename__ = 'user_account'
id = Column(Integer, primary_key=True)
name = Column(String(30))
fullname = Column(String(30))
address = relationship("Address", back_populates="user",cascade = 'all, delete, delete-orphan')
在创建User 对象,找不到Address 类定义,问题在于Users 类和Address 类各自继承了不同的Base 对象, Users 类通过自身继承的Base2 查找子类为Address 时是不会存在的,解决: 声明同一个declarative_base()对象,所有的model 类继承公共的base 类;
declarative_base() 作用:
- 子类通过继承declarative_base() 创建出的Base 类,在数据库中创建的表和这些子类之间可以进行关联关系映射