2016-04-15 63 views
0

我有這樣一個模型:Django的多個查詢過濾器 - 1場或2場

class Result(models.Model): 
    title = models.CharField(max_length=300) 
    desc = models.TextField(max_length=800) 
    url = models.CharField(max_length=200) 
    rank = models.BigIntegerField() 
    category = models.ForeignKey('Category') 
    tags = TaggableManager() 
    def __str__(self): 
     return self.title 
    class Meta: 
     verbose_name_plural = "Risultati" 

class Category(models.Model): 
    title = models.CharField(max_length=300) 
    slug = models.SlugField(null=True) 
    def __str__(self): 
     return self.title 
    class Meta: 
     verbose_name_plural = "Categorie" 

和看法:

def search_form(request): 
    return render(request, 'search.html') 

def result(request): 
    if 'q' in request.GET and request.GET['q']: 
     q = request.GET['q'] 
     results = Result.objects.filter(tags__name__in=[q], desc__icontains=q).order_by('-rank') 
     return render(request, 'results.html', {'results': results, 'query': q}) 
    else: 
     return render(request, 'search.html', {'error': True}) 

def detail(request, result_id): 
    try: 
     result = Result.objects.get(pk=result_id) 
    except Result.DoesNotExist: 
     raise Http404("Nessun risultato :(") 
    return render(request, 'detail.html', {'result': result}) 

我需要通過過濾器,標籤或遞減搜索,我嘗試連接過濾器()。filter()但沒有發生,錯誤在哪裏?

回答

0

在相同的filter()中或在單獨的鏈接中的鏈接表達式執行隱式的AND。如果您想要執行OR或明確AND,則需要使用Q objects

....filter(Q(tags__name__in=[q]) | Q(desc__icontains=q)).... 
+0

謝謝你,完美! – user0111001101