'Django Query - How can do Prefetch filter with values based on root query?

For better performance, i use prefetch selected to get all in one single query like this

profile = Profile.objects.only('id','series_following').prefetch_related(
        Prefetch('books_reading', queryset=Book.objects.only('id').filter(
                series_id=`series_following_id`), to_attr='books')).get(user=request.user_id)

I want to get all books are reading with series_following, but i dont know how to put it to filter. Here are my models:

class Profile(models.Model):
    user = models.OneToOneField(User)
    series_following = models.ForeignKey('Series')
    books_reading = models.ManyToManyField('Book', related_name="readers_reading_book",         
        null=True, blank=True)
    ...

class Series(models.Model):
    name = models.CharField()
    ...

class Book(models.Model):
    name = models.CharField()
    series = models.ForeignKey(Series)
    ...


Solution 1:[1]

Not sure your models are wired as you might expect them to be, but how about something like this?

user = request.user

books = Book.objects.filter(
    series = user.profile.series_following
)

That will get you all the books that a have the same series as the one a user is following based on their profile.

Solution 2:[2]

You can obtain the Books with:

Book.objects.filter(
    series__readers_reading_book__user=request.user
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel
Solution 2 Willem Van Onsem