2017-05-18 17 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") 
    ... 
相關問題