Search code examples
pythondjangodjango-modelsdjango-filters

Conditional search in django filter


I want to retrieve some data from my database in this way

from .models import Student

#activity is a many to many field

students = Student.objects.filter(name="doe",activity__name__icontains='a' or 'b').distinct().all()

This will work 👆.

But my problem is I have a list of items to check against the activities and if I try it like this 👇... it fails

activities = ['a','b','c']
students = Student.objects.filter(name="doe",activity__name__icontains=activities).distinct().all()

The length of the list is not constant it always varies.

I would appreciate any helping hand.

Thank you


Solution

  • The first one does not work, it will never match with things that do not contain 'a', but contain 'b'. The or will inspect the truthiness of 'a', and thus never take 'b' into account.

    As for the list, you can work with a Q object here:

    from django.db.models import Q
    
    activities = ['a','b','c']
    activity_filter = Q(
        *[('activity__name__icontains',activity) for activity in activities],
        _connector=Q.OR
    )
    
    students = Student.objects.filter(activity_filter, name='doe').distinct()