django多个查询过滤器 - 匹配1或2个字段

时间:2016-04-15 22:35:58

标签: django filter field match

我有一个这样的模型:

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

我需要通过过滤器,标签或者desc进行搜索,我尝试连接filter()。filter()但是什么都没发生,哪里出错?

1 个答案:

答案 0 :(得分:0)

在同一个filter()中或在单独的AND中链接表达式会执行隐式OR。如果您要执行AND或明确....filter(Q(tags__name__in=[q]) | Q(desc__icontains=q)).... ,则需要使用Q objects

static void Main(string[] args)
    {
        string[] StringNumbers = File.ReadAllLines("../Program/Files/Numbers.txt");
        double[] Double = StringNumbers.ToList().ConvertAll(x=>Convert.ToDouble(x)).ToArray();
    }