2017-05-18 16 views
-2

我正在学习python和sqlalchemy,并模拟商店和区域设置之间的这种关系。我得到的错误:
在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'

当我尝试从数据库中检索一个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

没有,离开了'back_populates',因为'Locale'没有* *店属性的关系。 –

+0

@IljaEverilä尝试并仍然得到相同的错误。我应该提到,我在iPython解释器 –

+0

中做了所有这些。这就是问题所在,你可能会在已经中断的会话中重复定义类。从头开始,移除'back_populates'。 –

回答

2

SQLAlchemy ORM关系不要求是双向的。如果使用back_populates参数,则可以这样声明它。使用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") 
    ... 
相关问题