我正在学习python和sqlalchemy,并模拟了商店和地区之间的这种关系。我收到错误:
InvalidRequestError:一个或多个地图制作者无法初始化 - 无法解决 继续初始化其他映射器。触发映射器: '映射器|商店|商店&#39 ;.原来的例外是:Mapper '映射器|区域设置|现场'没有财产' shop'
当我尝试从db中检索一个lolcale时。
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)
答案 0 :(得分:4)
SQLAlchemy ORM关系不需要是双向的。如果使用back_populates
参数,你就是这样声明的。使用back_populates
要求您也声明另一端:
采用字符串名称并且与
backref
具有相同的含义,但补充属性是不自动创建,而必须在其他映射器上显式配置。补充属性还应指明back_populates
这种关系,以确保正常运作。
(后者强调我的)
由于你没有在另一端声明该属性,SQLAlchemy抱怨道。只需删除back_populates
参数:
class Shop(maria.Base):
...
country = relationship("Locale")
...