Thursday, May 28, 2020

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

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 <manvityagi770@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-users+unsubscribe@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/CAK4qSCeXR_gD7HLQeYGNZ3q2OTfV7WkdTmJA1VmN_X0wszu9Cw%40mail.gmail.com.

No comments:

Post a Comment