2015-10-05 93 views
1

我想在django中查找表中以一組字符串中的一個字符串開頭的所有元素。我知道我們可以使用__startswith進行過濾,以查找以字符串開頭的元素,並且我們還可以使用__in進行過濾以查找一組數字。我如何合併它們?在Django中通過一組字符串進行過濾

例如,對於這種模式

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

假設我有三個要素:

  1. 1.01.2 ---- Object1
  2. 1.02.3 ----對象2
  3. 1.03.4 ---- Object3

因此,我想要一個過濾器,它允許我同時在列表L中找到以某個字符串開始的對象,其中L在本例中爲[「1.01」,「1.02」]。

回答

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

它動態地構建這樣保管其name開始與1.011.02對象的查詢:

>>> Inventary.objects.filter(Q(name__startswith='1.01') | Q(name__startswith='1.02')) 
0

你可以連續使用多個過濾器是這樣的:

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

你好hsfzxjy,謝謝你的回答,但我想要做到這一點。例如,要將字符串過濾爲可以更改的列表[「1.01」,「1.02」]。 – henryr

+0

不幸的是,在SQL中沒有這樣的功能,也沒有django ORM。您可以通過使用循環將過濾條件鏈接在一起來實現此目的。 – hsfzxjy