Quantcast
Channel: How to combine multiple querysets in Django? - Stack Overflow
Viewing all articles
Browse latest Browse all 32

Answer by chidimo for How can I combine two or more querysets in a Django view?

$
0
0

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 reducefrom queryset_sequence import QuerySetSequencecombined_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 reducefrom django.shortcuts import render    from queryset_sequence import QuerySetSequenceclass 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})

Viewing all articles
Browse latest Browse all 32

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>