how to use **kwargs if filters contains list of values

90 views
Skip to first unread message

Manvi Tyagi

unread,
May 28, 2020, 6:46:11 AM5/28/20
to Django users
i have a dict of filters , 
something like

{
    "name": "string",
    "status": [
      "A", "B"
    ],
    "reg": "string",
    "oc": [
      "As","jb"
    ]
  }


```query_set = query_set.filter(**filters)``` This works fine for all the filters whose type is not list , How do apply the filters on list values?
PS: I know about __in know I can do something like 
  # if status_list:
        #     query_set = query_set.filter(status__in=status_list)

BUT , 
1. I dont want to use if else statemnets
2. I want to have dynamic variables in the filters arguments and not hardcore ones like status__in

Andréas Kühne

unread,
May 28, 2020, 8:07:33 AM5/28/20
to django...@googlegroups.com
Simply put - you can't..... not without if statements.

What I would do is something like this:

query = Q()

for item in kwargs.items():
  if isinstance(item[1], list):
    query &= Q(**{f"{item[0]}__in": item[1]})
  else:
    query &= Q(**{item[0]: item[1]})

query_set = query_set.filter(query)

Regards,

Andréas


--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/47e6ae26-82c9-433c-8de3-08b303004864%40googlegroups.com.

Manvi Tyagi

unread,
May 29, 2020, 12:11:16 AM5/29/20
to Django users

Yes Andreas Kuhne, I ultimately went with something like this only!!
Thanks for the reply.
To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages