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

2024-05-29 11:38:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python和sqlalchemy,并对商店和语言环境之间的关系进行了建模。我得到错误:

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'

当我试图从数据库中检索棒棒糖时。在

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)

Tags: keyfromselftruestringsqlalchemycolumnshop
1条回答
网友
1楼 · 发布于 2024-05-29 11:38:25

SQLAlchemy ORM关系不需要是双向的。如果使用^{}参数,则说明它是这样的。使用back_populates还需要声明另一端:

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.

(后重点是我的)

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

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

相关问题 更多 >

    热门问题