2017-08-06 35 views
1

兩個型號如下:瓶:如何檢查一個一對多backref的存在

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 %} 

的如果其他條件都不能去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作品?

+0

嘗試在將python代碼傳遞給模板文件之前,在您的python代碼中打印user.comments。 – stamaimer

回答

0

這是當你寫if user.comments它永遠是真實的,因爲它不是無作爲容易解釋,即使是空當:

>>> user.comments 
<sqlalchemy.orm.dynamic.AppenderBaseQuery object at 0x7fa6e0b456a0> 
>>> user.comments.all() 
[] 

你看,即使無返回值,它的類型不是無,它是一個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 %} 
+1

人們可能更喜歡使用'user.comments.exists()'。或者更好的是,爲用戶的評論顯示的觀點提供熱切的評論。 – krassowski

+0

我正在考慮{%if user.comments.count()> 0%}做的東西 {%else%}還沒有評論{%endif%} 但是,您在這裏有很多選擇。我編輯了我的回覆以包含模板 – Fernando

相關問題