Django Boolean Queryset Filter Not Working

匿名 (未验证) 提交于 2019-12-03 08:35:02

问题:

This has been frustrating me for the better part of an hour.

I have the following model:

sold= models.BooleanField(default=False) 

And the following view code:

properties = Property.objects.filter(sold=False).order_by('-created_on'); 

And the following values in my sqlite3 database:

 sqlite> select sold from clients_property; 1 1 1 1 1 

And the following template code DOES work (as in, hides the sold items):

{% if not property.sold %} 

Anyone know why the query set filter isn't working or why I'm doing it wrong? I've tried:

sold="1" sold=1 sold="false" sold=False sold="False" 

回答1:

From what you've posted, everything is working as advertised. If you try this stuff from the shell, you should get the following results. Of course I'm making some of it up, so read before you just copy-paste.

>>> from myapp.models import Property >>> Property.objects.all() [<Property: Property object>,<Property: Property object>,<Property: Property object>,<Property: Property object>,<Property: Property object>,] >>> Property.objects.filter(sold=False) [] >>> Property.objects.filter(sold=True) [<Property: Property object>,<Property: Property object>,<Property: Property object>,<Property: Property object>,<Property: Property object>,] >>> Property.objects.create(sold=False, my='other', fields=1) >>> Property.objects.filter(sold=False) [<Property: Property object>,] 

Jack is right, 1 should evaluate to True in most SQL implementations.



回答2:

This has happened to me as well.

Turned out in SQLite you can have Boolean with value 0 and Boolean with value False

So Django does not work wiht the ones set to False

I saw this discrepancy in sqliteman

Simple update fixed the problem.

I think this happened during schema upgrades and migration in my dev environment so am not too worried about it.



回答3:

I had the same problem. My solution was to change the type of the column from a 'bit' to a 'tinyint'.

The issue in my case was caused by a manually added column in a table.



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