两种型号如下:
class Comment(db.Model):
__tablename__ = 'comments'
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.Integer, db.ForeignKey('users.id'))
class User(db.Model, UserMixin):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
comments = db.relationship('Comment', backref='author', lazy='dynamic')
user = User.query.get_or_404(id)
确保该用户存在,并且尚未发表任何评论。
然后在模板文件中
{% if user.comments %}
do stuff
{% else %}
no comments yet
{% endif %}
if-else 条件无法转到 else 分支。
如果我使用如下代码:
comments = Comment.query.filter_by(author_id=user.id).all()
{% if comments %}
do stuff
{% else %}
no comments yet
{% endif %}
可以输出
no comments yet
为什么 user.comments 不起作用?
最佳答案
很容易解释为,当您编写 if user.comments
时,它始终为 True,因为它不是 None,即使为空:
>>> user.comments
<sqlalchemy.orm.dynamic.AppenderBaseQuery object at 0x7fa6e0b456a0>
>>> user.comments.all()
[]
你会看到,即使查询没有返回任何内容,它的类型也不是 None,它是一个 sqlalchemy 对象:
>>> type(user.comments)
<class 'sqlalchemy.orm.dynamic.AppenderBaseQuery'>
也许你可以使用 len() 或直接使用 user.comments.all(),或者更好:
{% if user.comments.count() > 0 %}
do stuff
{% else %}
no comments yet
{% endif %}
关于python - Flask:如何检查一对多反向引用是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45533306/