henryr
henryr

Reputation: 169

Filtering in Django by a set of String

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"].

Upvotes: 1

Views: 841

Answers (3)

Dieu le veut Nkenye
Dieu le veut Nkenye

Reputation: 81

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

Upvotes: 0

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52093

>>> 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'))

Upvotes: 6

hsfzxjy
hsfzxjy

Reputation: 1322

You can chain multiple filters like this:

model.objects.filter(name__startswith='1.01').filter(name__startswith='1.02')

Upvotes: 0

Related Questions