Fetch similar Django objects in one query if the objects have no direct relation

Let's say I have the following model:

class Book(models.Model):
    class Meta:
      constraints = [
          models.UniqueConstraint(
              fields=["name", "version"],
              name="%(app_label)s_%(class)s_unique_name_version",
          )
      ]

    name = models.CharField(max_length=255)
    version = models.PositiveIntegerField()

For each book, I need to get all higher versions:

book_to_future_book_mappings = {}
for book in Book.objects.all():
    higher_versions = Book.objects.filter(name=name, version__gt=book.version).order_by("version")
    book_to_future_book_mappings[book] = list(higher_versions)

The problem with this approach is that it doesn't scale well. It makes a separate query for every book, which is very slow if I have millions of books in my database.

Is there anyway I can get all of this data in just a few queries? Perhaps I can use RawSQL if needed?

Note my database is PostgreSQL.

Back to Top