检查多个ORM关系的字段是否包含值

时间:2016-02-26 17:07:59

标签: python orm flask sqlalchemy flask-sqlalchemy

请求(我正在搜索的对象),该用户由分配了角色的用户组成,由所述请求表示。见下文:

class Request(db.Model):
    __tablename__ = 'requests'
    id = Column(Integer, primary_key=True)
    user = Column(Integer, ForeignKey("users.id"), nullable=False)
    role = Column(Integer, ForeignKey("roles.id"), nullable=False)
    ...

我们的关系:

# Define relationship between a User and their Requests
requests = relationship('Request', backref='requested_by', lazy='dynamic')

# Define relationship between a Role and Requests for this Role
requests = relationship('Request', backref='requested_role', lazy='dynamic')

最后,目标:

# Return any requests made by a user or a role matching the search query
data = Request.query.filter(or_(Request.requested_by.name.contains(search_query),
                                Request.requested_by.username.contains(search_query),
                                Request.requested_role.name.contains(search_query))).all()

运行上面的代码会产生以下结果:

AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Request.requested_by has an attribute 'name'

这里的想法是能够通过用户的相关详细信息或与之关联的角色来搜索Request对象。这可能吗?

1 个答案:

答案 0 :(得分:1)

是。您需要进行加入:

Request.query.join(Request.requested_by) \
             .join(Request.requested_role) \
             .filter(or_(User.name.contains(search_query),
                         User.username.contains(search_query),
                         Role.name.contains(search_query)))

请注意,这会产生LIKE '%whatever%'个查询,如果您有一个大表,这些查询效率非常低。