How to make null/none count 0 instead?

大城市里の小女人 提交于 2021-01-29 05:02:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!