Can django prefetch related work with 3 lookups?

I want to prefetch 3 tables plus the initial table. Here are model examples of the project i am working on

class ExampleOne(models.Model):
      name = models.Charfield()
      option = models.BooleanField()
      money = IntegerField()

class ExampleTwo(models.Model):
      word = models.Charfield()
      example_one = models.ManyToManyField(ExampleOne)
      number = IntegerField()

class ExampleThree(models.Model):
      number = models.IntegerField()
      example_two = models.ForeignKey(ExampleTwo)

      def get_calculation_one(self):
          Calculate using data from Example_2 and Example_1

class ExampleFour(models.Model):
      date = models.DateField()
      example_three = models.ManyToManyField(ExampleThree)

      def get_calculation_two(self):
          Calculate using data from method on Example_3

Now I want to know if it is possible to retrieve data from all these models with as little hits to the database as possible because when I try to retrieve data it takes over one minute to retrieve the data and send it to the frontend

The calculation might be making many database hits in order to get the data and calculate and i think that is why it is taking more than a minute to retrieve the data

my view looks like this

        qs = ExampleFour.objects.prefetch_related(
             Prefetch('example_three__example_two__example_one')
        ).filter(...)

Is there a way to use prefetch to make the retrieval faster or is there another suggestion on I can rewrite my code in order to avoid this long retrieval time?

Note I am still new to Django

Back to Top