Home > Blockchain >  How to make 2 queryset lists but with different filter in the same view in Django
How to make 2 queryset lists but with different filter in the same view in Django

Time:08-24

I've been searching an answer to this everywhere. How to make 2 queryset lists but with different filter in the same view? Should I make a class and separate functions inside for each list or one function and make querysets 2 times?

CodePudding user response:

If you want to append two of the same model querysets together, the following should work:

queryset_one = mymodel.objects.filter(id__range=[0,99])
queryset_two = mymodel.objects.filter(name__in=[john,jane])

full_queryset = queryset_one | queryset_two

The pipe operator is used to append querysets together.

If you need two different querysets to be passed into the view:

def index(request):
    queryset_one = mymodel.objects.filter(id__range=[0,99])
    queryset_two = mymodel.objects.filter(name__in=[john,jane])
    context{
        "queryset_one":queryset_one,
        "queryset_two":queryset_two
    }
    return render(request,'mypage.html',context)

CodePudding user response:

If your two filter for one model

from django.db.models import Q

Model.objects.filter(Q(x=10) | Q(active=False))

If for two modle

Q1 = model.object.filter(x=10)
Q2 = model_2.object.filter(active=False)
Q2_Q1 = Q1.union(Q2)
  • Related