Friday, April 10, 2015

Re: Help with the following query please

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



--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20150410120355.4045866e%40bigbox.christie.dr.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment