Django Resuable QuerySet

I have a QuerySet in a view similar to the one below. I would like to be able to use the same request to other views, but I do not want to copy and paste the code. It also seems that I break the stern principal.

If I want to change the request later, I will have to change it in all of my views, which is clearly not ideal. Is there a class that I have to create, or a method in my model that would allow me to call it from different angles? Does anyone have any advice on this?

tasks = Task.objects.filter(user = request.user).order_by('-created_at', 'is_complete')

+4
source share
1 answer

One solution would be to create a class in the model or extend the model manager.

from django.db import models

  • Adding a classmethod

     class MyModel(models.Model): @classmethod def get_user_tasks(cls, user): return cls.objects.filter(...).order_by(...) 
  • Redefinition manager

     class MyModelManager(models.Manager): def get_user_tasks(self, user): return self.filter(...).order_by(...) class MyModel(models.Model): objects = MyModelManager() # and in the view... queryset = MyModel.objects.get_user_tasks(request.user) 
+3
source

All Articles