Thursday, May 28, 2020

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


Yes Andreas Kuhne, I ultimately went with something like this only!!
Thanks for the reply.


On Thursday, May 28, 2020 at 5:37:33 PM UTC+5:30, Andréas Kühne wrote:
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


Den tors 28 maj 2020 kl 12:45 skrev Manvi Tyagi <manvit...@gmail.com>:
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

--
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...@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.

--
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 view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a2fb9e0c-1c8b-46b4-a7f5-ac801a67ed37%40googlegroups.com.

No comments:

Post a Comment