Solution to not split logic in django to solve N+1 queries

Here are some of my models:

class CustomUser(AbstractUser):
    def correct_date(self, date=None):
        res = self.dates.order_by("date").all()
        if not len(res):
            return None
        return res[len(res) - 1]


class Date(models.Model):
    user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name="dates")
    date = models.DateField(auto_now_add=True)

To fix N+1 queries I need to extract the order_by in the view with a Prefetch:

queryset = Project.objects.prefetch_related(
        Prefetch(
            "user__dates",
            queryset=Date.objects.order_by('date')
        ),
)

and remove the order_by in my correct_date method.

The problem here is that correct_date depends on the order_by in order to retrieve the last date. But the order_by is in an other file. That could leeds to issues for the ones using the code after.

Is there any other solutions than:

  • Keeping the code as it is with a comment # needs to be used with an order_by('date') before
  • Using a service to handle all that logic
  • Checking in the correct_date method if it was called with an order_by before, and throwing an error or apply order_by if it wasn't
Вернуться на верх