对于我的自引用表查询,它不能将集合与对象或集合进行比较;

时间:2017-09-10 09:40:19

标签: python flask sqlalchemy flask-sqlalchemy

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.

1 个答案:

答案 0 :(得分:0)

您的parent_place关系错误。您需要的是many-to-one关系。

请参阅Adjacency List Relationships

  

这里的relationship()配置与“普通”一对多关系的工作方式相同,但“方向”除外,即关系是一对多还是多对多关系一,默认假设是一对多。要建立多对一关系,需要添加一个名为remote_side的额外指令,它是Column对象或Column对象的集合,用于指示应被视为“远程”的对象:

您应该声明parent_place关系:

parent_place = db.relationship("Place", remote_side=[id])

  

如果在上面,id列被应用为父关系()的remote_side,从而将parent_id建立为“本地”一侧,然后该关系表现为多对一。