Django-按“确定值或无”进行过滤; [英] Django - filtering by "certain value or None"

查看:74
本文介绍了Django-按“确定值或无”进行过滤;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据对象中有一个字段,该字段可以为null或设置为某个整数。我想给定一个整数,以该整数值过滤所有对象或不过滤任何对象:

I have a field in an data object that can be either null or set to some integer. I want, given an integer, to filter all the objects with that integer value OR none:

MyElements.objects.all().filter(value__in=[myInt, None])

但是,此行不适用于带有空值。更精确地说:

However, this line does not work for elements with null value. More precisely:

MyElements.objects.all().filter(value__in=[None])

不返回任何内容。而

MyElements.objects.all().filter(value = None)

返回空值元素。

如何重写原始查询(涉及到myInt)正确?

How can I rewrite the original query (which involves myInt) correctly?

推荐答案

您可以使用 Q值,可让您在Django查询集中组合多个子句。

You can use Q values which allow you to combine multiple clauses in Django querysets.

您的查询集将类似于:

from django.db.models import Q
MyElements.objects.all().filter(Q(value=None) | Q(value=myInt))

这篇关于Django-按“确定值或无”进行过滤;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆