Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Boolean Queryset Filter Not Working

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"
like image 674
John Peebles Avatar asked Aug 03 '11 20:08

John Peebles


3 Answers

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 with 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 I am not too worried about it.

like image 54
Kiril Avatar answered Oct 23 '22 16:10

Kiril


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.

like image 34
Issac Kelly Avatar answered Oct 23 '22 15:10

Issac Kelly


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.

like image 1
The Doc Avatar answered Oct 23 '22 17:10

The Doc