Adding annotations to all querysets with a custom QuerySet as Manager

前端 未结 1 1660
天涯浪人
天涯浪人 2021-01-04 22:23

I\'m not sure how to put words on this precisely, but what I\'m trying to do is use a custom QuerySet for a model, but I want to annotate the results of any queryset. So whe

1条回答
  •  一生所求
    2021-01-04 23:07

    You should use the from_queryset method - it allows you to create a Manager class which you can further customise before applying to your model. For example:

    class CustomQuerySet(models.QuerySet):
        def most_liked(self):
            return self.filter(...)
    
    
    class CustomManager(models.Manager.from_queryset(CustomQuerySet)):
        def get_queryset(self):
            return super(CustomManager, self).get_queryset() \
                .annotate(...)
    
    
    class Model(models.Model):
        objects = CustomManager()
    

    0 讨论(0)
提交回复
热议问题