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