Filtering in Django by a set of String

Question:

I want to find in django, all the elements in a table that start with one string in a set of strings. I know that we can filter with __startswith to find the elements that start with a string, and also, we can filter with __in to find into a set of numbers. How I can merge them?

For example, for this model

class Inventary:
    code = models.CharField(max_length=10)
    name = models.CharField(max_length=150)

Suppose that I have the three elements:

  1. 1.01.2 —- Object1
  2. 1.02.3 —- Object2
  3. 1.03.4 —- Object3

Thus, I want a filter that allow me find the Objects that start with some string in the list L at the same time, where L in this case is [“1.01″,”1.02”].

Asked By: henryr

||

Answers:

You can chain multiple filters like this:

model.objects.filter(name__startswith='1.01').filter(name__startswith='1.02')
Answered By: hsfzxjy
>>> from django.db.models import Q

>>> values = ['1.01', '1.02']

>>> query = Q()
>>> for value in values:
...     query |= Q(name__startswith=value)

>>> Inventary.objects.filter(query)

It dynamically builds a query that’ll fetch the objects whose name starts with 1.01 or 1.02:

>>> Inventary.objects.filter(Q(name__startswith='1.01') | Q(name__startswith='1.02'))
Answered By: Ozgur Vatansever

this worked for me

>>> from django.db.models import Q

>>> values = ['1.01', '1.02']

>>> objects = Inventary.objects
>>> for value in values:
...     objects = objects. filter(name__startswith=value)

>>> objects
Answered By: Dieu le veut Nkenye
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.