3
Channel.query.filter(Channel.is_default == True).all()

When I use above expression it works,but an pep8 advice is occuered.So I use below expression instead.

Channel.query.filter(Channel.is_default is True).all()

But when I run the code, no data returned.And there is no error or warning.

Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
霖同学
  • 33
  • 4
  • Does this answer your question? [flake8 complains on boolean comparison "==" in filter clause](https://stackoverflow.com/questions/18998010/flake8-complains-on-boolean-comparison-in-filter-clause) – Julio Cezar Silva Jun 19 '20 at 18:39

1 Answers1

1

~When you're dealing with a property or method that returns boolean values, there is absolutely no need to compare it with True or False. It's a bad practice, even.

So, to solve both your PEP8 problem, and your filtering one, just omit the comparison, since Channel.is_default will already yield True or False individually:

Channel.query.filter(Channel.is_default).all()

And if that filter doesn't give you any results, it's because not all within your Channel have is_default set to True. This filter is as straightforward as they come.

Edit: my answer was misinformed, the filter function in sqlalchemy is a very particular case of conditionality in Python. See this question and its most prominent answers, which also answer OP's question as of now.

Julio Cezar Silva
  • 2,148
  • 1
  • 21
  • 30
  • Thanks for your answer.Now I know how to solve PEP8.But I have no idea about what do you mean in the final paragraph.In the database,is_default field is a bollean field.(0 or 1)And there are some records set is_default to 1.So i can get data with the expression: Channel.query.filter(Channel.is_default == True).all().True can be replace with 1.But replace '==' with is will get no data.That is the most important part! – 霖同学 Jun 19 '20 at 00:43
  • By the way, I just tried your expression and it did work.Now I wonder how to judge 'Channel.is_default' to be False.Thanks. – 霖同学 Jun 19 '20 at 00:58
  • The fact that the field is binary doesn't matter, since Python considers 0 to be False and 1 to be True in conditional structures (check the [truthy-falsy in Python](https://freecodecamp.org/news/truthy-and-falsy-values-in-python)). But I've just noticed your question is duplicated, see [here](https://stackoverflow.com/questions/18998010/flake8-complains-on-boolean-comparison-in-filter-clause). I won't update my answer since it was misinformed to begin with, but you can do as the first or second answers suggest – Julio Cezar Silva Jun 19 '20 at 17:07