Search code examples
pythondjangolistdjango-modelsdjango-queryset

How to do a Django list in list query


I have a list of lists filter items as this: [['3aa', '1ss', '2bb'], ['4aa', '5bb'], ['3nn', '9mm', '6cc']]

My database table has a field with a field(category) holding a list as value: ['4aa', '5bb'] How can I query to fetch items whose category is in the filter list?

Something like:

Table.objects.filter(category__in=[['3aa', '1ss', '2bb'], ['4aa', '5bb'], ['3nn', '9mm', '6cc']])

Model:
Class Table(…):
   category = models.jsonfield()

Solution

  • Does exact lookup work ? (Table.objects.filter(category=['3aa', '1ss', '2bb']))
    If so you can use Q objects

    q_conditions = Q()
    for categories in categories_list:
        q_conditions |= Q(category=categories)
    
    Table.objects.filter(q_conditions)