Home > database >  How to convert list to multiple Q objects?
How to convert list to multiple Q objects?

Time:07-03

Taking an example from Django 3.2 documentation, I need to use an argument like this for .filter:

Q(question__startswith='Who') | Q(question__startswith='What')

In my case need to convert each of the user's selections, which I'm getting in views.py via request.META['QUERY_STRING'], into it's own Q() object.

If I tried to create Q objects from that list of parameters, it would not work, because the | would be evaluated. This seems like it must be a solved a problem, but I haven't had luck yet finding the answer. Thanks for any advice.

CodePudding user response:

You can build up a complex Q object in a loop - use q_obj |= Q(...) to add another Q with OR

selections = ['Who', 'What']
or_expr = Q()
for selection in selections:
    or_expr |= Q(question__startswith=selection)
MyModel.objects.filter(or_expr)

CodePudding user response:

using regex might be an easy option:

Model.objects.filter(question__iregex="^(What|Who).*"gm)

CodePudding user response:

You can do that using distnict()

.filter(Q(question__startswith='Who') | Q(question__startswith='What')).distnict()
  • Related