Do all relationships modeled in SQLAlchemy have to

2019-09-17 08:16发布

问题:

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")
    ...