SQLAlchemy - 一次搜索三个表

时间:2012-07-01 10:46:20

标签: python mysql sqlalchemy flask flask-sqlalchemy

修改 请原谅,因为我刚刚意识到我在下面的例子中犯了一个错误。这就是我想要实现的目标:

假设我有如下所述的三个表格。当用户输入查询时,它将在所有三个表中搜索名称为LIKE%query%的结果,但仅返回唯一结果。

以下是一些示例数据和输出:

数据:

**Grandchild:**
id: 1
name: John
child_id: 1

**Grandchild:**
id: 2
name: Jesse
child_id: 2

**Child:**
id: 1
name: Joshua
parent_id: 1

**Child:**
id: 2
name: Jackson
parent_id: 1

**Parent:**
id: 1
name: Josie

如果用户搜索“j”,它将返回两个孙子条目:John和Jesse。 如果用户搜索“j,Joshua”,它将只返回孩子是约书亚的孙子孙女 - 在这种情况下,只有约翰。

基本上,我想搜索所有孙子条目,然后如果用户键入更多关键词,它将根据相关的子条目名称过滤掉孙子孙。 “j”将返回以“j”开头的所有孙子,“j,Josh”将返回以“j”开头的所有孙子,并且他们的孩子就像他们的孩子一样Josh%。


所以,我有这样的设置:

Grandchild{
   id
   name
   child_id
}

Child{
   id
   name
   parent_id
}

Parent{
   id
   name
}

孙子被链接/映射到孩子。 Child映射到Parent。

我想做的是,如下所示,我一次搜索所有三个数据库:

return Grandchild.query.filter(or_(
  Grandchild.name.like("%" + query + "%"),
  Grandchild.child.name.like("%" + query + "%"),
  Grandchild.child.parent.name.like("%" + query + "%")
)).all()

显然上面的查询不正确,并返回错误:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'name'

对于我正在尝试的内容,正确的方法是什么?

我正在运行MySQL,Flask-SQLAlchemy(我认为扩展了SQLAlchemy),Flask。

1 个答案:

答案 0 :(得分:2)

就我而言,最好修改数据模型(如果可能的话)。 您可以创建一个自我引用的表'People':

People
{ 
    id,
    name,
    parent_id,
    grandparent_id,
 } 

class People(Base):
    __tablename__ = "people"

    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(Unicode(255), nullable=False)
    parent_id = Column(Integer, ForeignKey('people.id'))       # parent in hierarchy
    grandparent_id = Column(Integer, ForeignKey('people.id'))  # grandparent in hierarchy

    # relationships
    parent = relationship("People", primaryjoin="People.parent_id==People.id", 
                          remote_side=[id])
    grandparent = relationship("People", primaryjoin="People.grandparent_id==People.id", 
                               remote_side=[id])

然后事情变得更加明显:

session.query(People).filter(People.name.like("%" + query + "%"))
相关问题