0

I want to only execute a prefect_related on my queryset when a boolean value in my database is True.

I have the following models:

from django.db import models

class Map(models.Model):
    has_ratings = models.BooleanField()

class Place(models.Model):
    name = models.CharField()
    map = models.ForeignKey(Map, on_delete=models.CASCADE)
    ...

class Rating(models.Model):
    rating = models.IntegerField()
    place = models.ForeignKey(place, on_delete=models.CASCADE)
    ...

Not every map has the rating functionality turned on. Therefore I only want to conditionally fetch the ratings and prevent the extra query to the Rating table for maps without ratings.

The query below always queries the Rating table.

Place.objects.all().prefetch_related(
    Prefetch(
        "ratings",
        queryset=Rating.objects.all(),
        to_attr="rating_list",
    )
)

So I tried to add a filter:

Place.objects.all().prefetch_related(
    Prefetch(
        "ratings",
        queryset=Rating.objects.all(),
        to_attr="rating_list",
    )
).filter(Q(map__has_rating=True))

This doesn't work because it filters all places for a Map with has_rating=False.

Is this doable without loading the map in memory? How can I can I make the prefetch optional based on a database value with Dango querysets?

TimS
  • 11
  • 2

0 Answers0