Help with the following query please

35 views
Skip to first unread message

Bryan Arguello

unread,
Apr 10, 2015, 12:39:47 PM4/10/15
to django...@googlegroups.com

This small example captures what I am actually trying to do in my application.

list = MyObject.objects.filter(field1 = entries1, field2 = entries2)

I want the query to just ignore "field2 = entries2" if entries2 is empty.  Or if entries1 is empty, I want it to ignore "field1 = entries1".

One thing I could do is just use logic to check whether entries1 or entries 2 is empty and create queries for each of the cases,

but my actual application has much more than two fields to check. 

Javier Guerra Giraldez

unread,
Apr 10, 2015, 12:55:19 PM4/10/15
to django...@googlegroups.com
On Fri, Apr 10, 2015 at 11:39 AM, Bryan Arguello <brome...@gmail.com> wrote:
> list = MyObject.objects.filter(field1 = entries1, field2 = entries2)

you can construct a dictionary and expand into function arguments:

list = MyObject.objects.filter(**{ f: e for f,e in (
('field1', entries1),
('field2', entries2),
.....)
if e is not None})


--
Javier

Tim Chase

unread,
Apr 10, 2015, 1:03:14 PM4/10/15
to django...@googlegroups.com
On 2015-04-10 09:39, Bryan Arguello wrote:
> list = MyObject.objects.filter(field1 = entries1, field2 = entries2)
>
> I want the query to just ignore "field2 = entries2" if entries2 is
> empty. Or if entries1 is empty, I want it to ignore "field1 =
> entries1".
>
> One thing I could do is just use logic to check whether entries1 or
> entries 2 is empty and create queries for each of the cases,

You can use Python's argument-unpacking:

args = {}
for name, value in [
("field1", entries1),
("field2", entries2),
]:
if value:
args[name] = value
# optionally test if we've added any filters
# if args:
lst = MyObj.objects.filter(**args)

(also, using "lst" so as not to shadow the built-in "list()")

In Python3, that can be reduced to a dict-comprehension:

args = {
name: value
for name, value in [
("field1", entries1),
("field2", entries2),
]
if value
}
# optionally test if we've added any filters
# if args:
lst = MyObj.objects.filter(**args)

Because the source of fieldname/value pairs doesn't have to be
statically included in your code, this offers some nice integration
with forms where things come from your fields.

-tkc



Javier Guerra Giraldez

unread,
Apr 10, 2015, 1:20:24 PM4/10/15
to django...@googlegroups.com
On Fri, Apr 10, 2015 at 12:03 PM, Tim Chase
<django...@tim.thechases.com> wrote:
> In Python3, that can be reduced to a dict-comprehension:


Python 2.7 included dict-comprehensions too

--
Javier

Bryan Arguello

unread,
Apr 10, 2015, 1:24:55 PM4/10/15
to django...@googlegroups.com
These are some beautiful solutions!  I completely forgot that I am programming in Python and
have all the convenience I want at my fingertips.

Your solution worked like a charm, Javier!  

Thank you both.

-Bryan
Reply all
Reply to author
Forward
0 new messages