python - Flask:如何检查一对多反向引用是否存在

标签 python flask sqlalchemy jinja2 flask-sqlalchemy

两种型号如下:

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/

相关文章:

python - 树状图标签重叠

python - 属性错误 : 'Options' object has no attribute 'binary' error invoking Headless Firefox using GeckoDriver through Selenium

python - Flask 应用程序未启动(类型错误 : code() takes at least 14 arguments (13 given))

python - 带有 Flask 'mongoengine.errors.NotRegistered' 问题的 mongoengine

sqlite - SQLAlchemy + SQLite左联接性能问题

python - NumPy 数组不是 JSON 可序列化的

python - 无法从线程显示窗口

python - Flask:如果字段不存在,则 current_app AttributeError

python - 如何从 SQlAlchemy ORM session 中查询预先存在的表?

python - 如何在 Alembic/SQLAlchemy 中使用 USING 子句?