filter queryset based on list, including None

Posted by jujule on Stack Overflow See other posts from Stack Overflow or by jujule
Published on 2010-04-26T22:11:20Z Indexed on 2010/04/26 22:13 UTC
Read the original article Hit count: 175

Filed under:
|
|
|
|

Hi all

I dont know if its a django bug or a feature but i have a strange ORM behaviour with MySQL.

class Status(models.Model):
    name = models.CharField(max_length = 50)

class Article(models.Model)
    status = models.ForeignKey(status, blank = True, null=True)


filters = Q(status__in =[0, 1,2] ) | Q(status=None) 
items = Article.objects.filter(filters) 

this returns Article items but some have other status than requested [0,1,2,None]

looking at the sql query :

SELECT [..] FROM `app_article` LEFT OUTER JOIN `app_status` ON (`app_article`.`status_id` = `app_status`.`id`) WHERE (`app_article`.`status_id` IN (1, 2) OR `app_status`.`id` IS NULL) ORDER BY [...]

the OR app_status.id IS NULL part seems to be the cause. if i change it to OR app_article.status_id IS NULL it works correctly.

How to deal with this ?

Thanx.

© Stack Overflow or respective owner

Related posts about django

Related posts about orm