简体   繁体   中英

django filter queryset based on count of another queryset

Assume my models:

model book 
    charfield name

model review
    charfield bookname

Is there a way to filter/exclude the books with review count zero? I looked this up throughly on stackoverflow but couldn't find an answer. This is not a homework question. I have a queryset approx. size around 200,000, from which I concluded that it is not smart to filter by converting the queryset to a python list, filter, then convert back. Can someone help me with this? Thanks

Because I strongly recommend changing your models to include a foreign key from review to book (for the many other benefits of doing that) rather than attempting to solve the exact problem you've asked about, I'm going to give you a hint on how to write your models with a foreign key and then how to solve the problem you've asked about in the context of a foreign key relationship.

Here are the new models I think you should write:

from django.db import models

class Book(models.Model):
    name = models.Charfield()

class Review(models.Model):
    book = models.ForeignKey(Book, related_name='reviews')

Then, to filter for all books having any reviews you could do:

books_with_reviews = Book.objects.filter(reviews__isnull=False).distinct()

Or for books without reviews:

Book.objects.filter(reviews__isnull=True).distinct()

First, you can query list of book which has review, and then get compliment by using django exclude

bookname_has_review = Review.objects.all().distinct().values_list('bookname', flat=True)
book_not_have_review = Book.objects.all().exclude(name__in=bookname_has_review)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM