How to combine two or more querysets in a Django view?

后端 未结 13 2406
猫巷女王i
猫巷女王i 2020-11-21 22:40

I am trying to build the search for a Django site I am building, and in that search, I am searching in 3 different models. And to get pagination on the search result list, I

13条回答
  •  北海茫月
    2020-11-21 23:24

    Requirements: Django==2.0.2, django-querysetsequence==0.8

    In case you want to combine querysets and still come out with a QuerySet, you might want to check out django-queryset-sequence.

    But one note about it. It only takes two querysets as it's argument. But with python reduce you can always apply it to multiple querysets.

    from functools import reduce
    from queryset_sequence import QuerySetSequence
    
    combined_queryset = reduce(QuerySetSequence, list_of_queryset)
    

    And that's it. Below is a situation I ran into and how I employed list comprehension, reduce and django-queryset-sequence

    from functools import reduce
    from django.shortcuts import render    
    from queryset_sequence import QuerySetSequence
    
    class People(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        mentor = models.ForeignKey('self', null=True, on_delete=models.SET_NULL, related_name='my_mentees')
    
    class Book(models.Model):
        name = models.CharField(max_length=20)
        owner = models.ForeignKey(Student, on_delete=models.CASCADE)
    
    # as a mentor, I want to see all the books owned by all my mentees in one view.
    def mentee_books(request):
        template = "my_mentee_books.html"
        mentor = People.objects.get(user=request.user)
        my_mentees = mentor.my_mentees.all() # returns QuerySet of all my mentees
        mentee_books = reduce(QuerySetSequence, [each.book_set.all() for each in my_mentees])
    
        return render(request, template, {'mentee_books' : mentee_books})
    

提交回复
热议问题