Home > other >  Django Query - How can do Prefetch filter with values based on root query?
Django Query - How can do Prefetch filter with values based on root query?

Time:03-10

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)
    ...

CodePudding user response:

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.

CodePudding user response:

You can obtain the Books with:

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