yvl
yvl

Reputation: 670

filter a column with a multiple keywords, in django

I am trying to filter a column in DB with a multiple keywords but having a problem. When I try to apply __contains= on an array it's doesn't work.

def get_tasks_by_filters(request):
    datas = json.loads(request.body)

    tasks = Task.objects.filter(task_name__contains=datas["keywords"])
    serializer = TasksPricesSerializers(tasks, many=True)

    return JsonResponse(serializer.data, safe=False)

And __contains= of course working with a single value Task.objects.filter(task_name__contains=datas["keywords"][0]) But how can apply __contains= on multiple keywords/array. What is the possible way to achieve this?

Upvotes: 0

Views: 183

Answers (1)

ruddra
ruddra

Reputation: 51998

You can try like this using Q():

from django.db.models import Q

query = Q()

for k in datas["keywords"]:
    query |= Q(task_name__contains=k)

tasks = Task.objects.filter(query)

Upvotes: 1

Related Questions