开发者

filter queryset based on list, including None

I dont kn开发者_开发问答ow 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.


Try using this query instead:

filters = Q(status__in =[0, 1,2] ) | Q(status__isnull=True) 


In your foreign key attribute for the Article model, you're referencing status with a lowercase 's'. But your Status model has an uppercase 'S'. Not sure where your typo is, but in case your model is actually defined with a lower case 's', then that might explain the strange SQL you're seeing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜