![](/img/trans.png)
[英]Sort objects by length of self-referencing child collection in SQLAlchemy
[英]For my self referencing table query it can't compare a collection to an object or collection;
class Place(db.Model):
__tablename__ = 'places'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
lat = db.Column(db.FLOAT, default=None)
long = db.Column(db.FLOAT, default=None)
parent_place_id = db.Column(db.Integer, db.ForeignKey('places.id'))
parent_place = db.relationship("Place")
branches = db.relationship("Branch", back_populates="place")
def __str__(self):
return self.name
當我嘗試執行以下操作時:
p_place = models.Place.query.get(parent_place_id) if parent_place_id else None
places = models.Place.query.filter(models.Place.parent_place==p_place ).all()
我收到以下錯誤:
Traceback (most recent call last):
...
File "./app/ecom_chatbot/ecom_conversation.py", line 127, in show_locations
places = models.Place.query.filter(models.Place.parent_place==p_place ).all()
File "/root/ecom/ecom_bot/local/lib/python2.7/site-packages/sqlalchemy/sql/operators.py", line 304, in __eq__
return self.operate(eq, other)
File "/root/ecom/ecom_bot/local/lib/python2.7/site-packages/sqlalchemy/orm/attributes.py", line 175, in operate
return op(self.comparator, *other, **kwargs)
File "/root/ecom/ecom_bot/local/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1037, in __eq__
"Can't compare a collection to an object or collection; "
sqlalchemy.exc.InvalidRequestError: Can't compare a collection to an object or collection; use contains() to test for membership.
您的parent_place
關系錯誤。 您需要的是many-to-one
關系。
請參閱鄰接表關系
這里的Relationship()配置與“正常”一對多關系的工作方式相同,不同之處在於“方向”(即關系是一對多還是多對一)是默認情況下假定為一對多。 為了建立多對一的關系,添加了一個額外的指令,稱為remote_side,它是Column或Column對象的集合,指示應被視為“遠程”的對象:
您應該這樣聲明您的parent_place
關系:
parent_place = db.relationship("Place", remote_side=[id])
在上面的地方,將id列用作父關系()的remote_side,從而將parent_id建立為“本地”端,然后該關系表現為多對一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.