在SQLAlchemy中建模的所有关系都必须是双向的吗?

时间:2017-05-18 09:38:54

标签: python sqlalchemy foreign-keys relational-database

我正在学习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)

1 个答案:

答案 0 :(得分:4)

SQLAlchemy ORM关系不需要是双向的。如果使用back_populates参数,你就是这样声明的。使用back_populates要求您也声明另一端:

  

采用字符串名称并且与backref具有相同的含义,但补充属性是自动创建,而必须在其他映射器上显式配置。补充属性还应指明back_populates这种关系,以确保正常运作。

(后者强调我的)

由于你没有在另一端声明该属性,SQLAlchemy抱怨道。只需删除back_populates参数:

class Shop(maria.Base):
    ...
    country = relationship("Locale")
    ...