Dar*_*ar1 3 python sqlalchemy foreign-keys relational-database
我正在学习 python 和 sqlalchemy,并对商店和语言环境之间的关系进行建模。我收到错误:
InvalidRequestError:一个或多个映射器初始化失败 - 无法继续初始化其他映射器。触发映射器:'Mapper|Shop|shop'。原始异常是:Mapper 'Mapper|Locale|locale' 没有属性 'shop'
当我尝试从数据库检索语言时。
from sqlalchemy import Column, ForeignKey, PrimaryKeyConstraint, String
from sqlalchemy.orm import relationship
class Shop(maria.Base):
__tablename__ = 'shop'
__table_args__ = {'extend_existing': True }
name = Column(String(25), primary_key=True)
locale = Column(String, ForeignKey('locale.country'), primary_key=True)
url = Column(String, nullable=False)
country = relationship("Locale", back_populates='shop')
def __repr__(self):
return "{\n\tname:'%s',\n\tlocale:'%s',\n\turl:'%s'\n}" % (self.name, self.locale, self.url)
class Locale(maria.Base):
__tablename__ = 'locale'
__table_args__ = {'extend_existing': True}
country = Column(String(50), primary_key=True)
code = Column(String(11), primary_key=True)
def __repr__(self):
return "{\n\tcountry:'%s',\n\tcode:'%s'\n}" % (self.country, self.code)
Run Code Online (Sandbox Code Playgroud)
SQLAlchemy ORM 关系不需要是双向的。如果使用back_populates参数,那么您就这样声明了它。使用back_populates要求您也声明另一端:
接受一个字符串名称,与 具有相同的含义
backref,除了补充属性不会自动创建,而必须在其他映射器上显式配置。补充属性还应表明back_populates这种关系,以确保正常运行。
(后面强调的是我的)
由于您尚未在另一端声明该属性,因此 SQLAlchemy 会抱怨。只需删除back_populates参数:
class Shop(maria.Base):
...
country = relationship("Locale")
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1142 次 |
| 最近记录: |