Do all relationships modeled in SQLAlchemy have to be bi-directional?

早过忘川 提交于 2020-01-17 06:44:49

问题


I am learning python and sqlalchemy and modelled this relationship between shops and locale. I get the error:

InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'Mapper|Shop|shop'. Original exception was: Mapper 'Mapper|Locale|locale' has no property 'shop'

when I try to retrieve a lolcale from the db.

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:


SQLAlchemy ORM relationships are not required to be bi-directional. If using back_populates argument you are declaring it as such though. Using back_populates requires that you declare the other end as well:

Takes a string name and has the same meaning as backref, except the complementing property is not created automatically, and instead must be configured explicitly on the other mapper. The complementing property should also indicate back_populates to this relationship to ensure proper functioning.

(Latter emphasis mine)

Since you've not declared the property at the other end, SQLAlchemy complains. Just remove the back_populates argument:

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


来源:https://stackoverflow.com/questions/44044089/do-all-relationships-modeled-in-sqlalchemy-have-to-be-bi-directional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!