问题
I have some sqlalchemy that counts rows with the value "3" and then prints out the count. It works fine if the count is 1, 2, 3, etc, but when there are no items, it prints nothing. I wanted it to print 0. So I added an if/else statement that didn't work (it prints nothing, no errors).
How would I do this? Here's my current code — not really sure if I should be doing this part in sqlalchemy or python.
q = (db.session.query(Article.snippet, sa.func.count(ArticleVote.id))
.join(ArticleVote, Article.id == ArticleVote.article_id)
.filter(Article.snippet == a_obj.snippet)
.filter(ArticleVote.vote_choice_id == 3)
.group_by(Article.snippet))
for snippet, count in q:
if count is None:
threevotes = 0
else:
threevotes = count
print(snippet, count)
print("threevotes", threevotes)
Update: I made it an outer join. That didn't help.
.join(ArticleVote, Article.id == ArticleVote.article_id, isouter=True)
Update: I found a workaround. I don't think it's the proper way to do things, and I'm concerned it might be problematic somehow in the future, so if anyone has a better idea (or can tell me whether or not this could be problematic) that'd be great.
if 'threevotes' in locals():
print("threevotes in locals")
else:
print("threevote not in locals")
threevotes= 0
来源:https://stackoverflow.com/questions/61686624/how-to-make-null-none-count-0-instead