拥有这个 SQLAlchemy 模型:
class Post(db.Model):
__tablename__ = 'posts'
post_id = db.Column(db.Integer, primary_key=True)
post_parent = db.Column(db.Integer, db.ForeignKey('posts.post_id'))
children = db.relationship('Post')
如您所见,Post 可以有子对象(即 Post_parent 不为 0 的 Post 对象)。对于我从数据库中检索到的每个 Post,都会生成一个 SELECT 来检索其子项。没关系。
但是,在我的数据库设计中,post_parent 不为 0 的 Post 不能有 child (即来自父帖子的 child 不能在其下有更多的 child )。但是检索它们的 SELECT 已生成。我怎样才能避免这种情况?
请您参考如下方法:
在关系术语中,这里的任何 Post 都可以有子 Post 对象,因为所有 Post 对象都有一个主键,所以可以有任意数量的 Post 对象具有 post_parent 的主键。所以说 somepost.children 必须发出 SQL,否则 SQLA 将不会提供正确的结果。如果你的模型有一些特殊规则,一些 Post 对象在不查询数据库的情况下已知没有 child ,你需要有条件地访问“somepost.children”。但是,从关系的角度来看,您断言“post_parent 不为 0 的发布对象不能有 child ”是不正确的。这种关系被配置为一对多,因此任何 Post 都可以有与其 post_parent 无关的 child 。
另一方面,如果您真的想让 Post.children 成为特定 Post 的单数、多对一,那么您需要在该关系上设置 remote_side=post_id(),在这种情况下,如果 parent_post 为 None,您将不会获得延迟加载(虽然不是零,但这是一个非 NULL 值)。
