Objects.filter(“我想添加两个包含字段”)

时间:2019-05-25 20:07:28

标签: python django

这是搜索字段。但是在视图中我无法在两个字段上搜索。我尝试了所有这些。它不起作用。 它仅在= Makale.objects.filter(baslik__contains = keyword)这样的一个字段中起作用

makale =  Makale.objects.filter(baslik__contains=keyword,icerik_contains=keyword)

makale = Makale.objects.filter(baslik_contains=keyword or icerik_contains=keyword)

def paylasimlar(request):
    keyword = request.GET.get("keyword")
    if keyword:
        paylasimlar = Makale.objects.filter(icerik__contains=keyword)
        return render(request, "feed.html", {"paylasimlar": paylasimlar})
    paylasimlar = Makale.objects.all()
    return render(request, "feed.html", {"paylasimlar":paylasimlar})

1 个答案:

答案 0 :(得分:1)

您可以使用Q-objects [Django-doc]or (|) operator [Django-doc]在两个约束之间添加运算符,例如:

from django.db.models import Q

Makale.objects.filter(Q(baslik__contains=keyword) | Q(icerik__contains=keyword))