Can the contents of a relationship be filtered when querying parent model?

江枫思渺然 提交于 2019-12-01 12:06:36
davidism

A relationship, by default, is a simple equality expression: Parent.id == ForeignKey.id. You cannot change the contents of a relationship at query time*, but you can create another relationship that selects only the items you want.

class PKMovie(db.Model):
    # ...
    future_show_times = db.relationship(
        lambda: ShowTime,
        primaryjoin=lambda: db.and_(
            PKMovie.id == ShowTime.pk_movie_id,
            ShowTime.date >= db.func.current_timestamp()
        ),
        viewonly=True
    )

Accessing an instance's future_show_times will return only the show times that are in the future. You can eager load this relationship during the query so that it doesn't incur an extra database query when accessed.

PKMovie.query.options(db.joinedload(PKMovie.future_show_times)).all()

See the documentation for relationships.


* Technically, you can change the relationship at query time, as demonstrated by this answer. However, I think it's much clearer to explicitly define these other relationships.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!