Posts

Showing posts with the label query-performance

Django: prefetch_related has no effect

Django: prefetch_related has no effect I'm trying to optimize a DB query using prefetch_related without success. prefetch_related class Order(models.Model): # some fields ... @property def last_operation(self) -> Optional['OrderOperation']: try: return self.orderoperation_set.latest() except OrderOperation.DoesNotExist: return None @property def total(self) -> Optional[Decimal]: last_operation = self.last_operation return last_operation.total if last_operation else None class OrderOperation(TimeStampable, models.Model): order = models.ForeignKey(Order) total = DecimalField(max_digits=9, decimal_places=2) orders = Order.objects.prefetch_related('orderoperation_set') # There are 1000 orders result = sum([order.total for order in orders]) len(connection.queries) >>> 1003 As we can see, there is one query per order.total , so 1000 queries, that makes the whole request ve...