Efficient way to order Annotate field in DRF

  Kiến thức lập trình

I have three models in models.py,

class AAA(models.Model):
    name = models.CharField(max_length=300, null=False, blank=False)

class BBB(models.Model):
    aaa = models.ForeignKey(AAA, on_delete=models.CASCADE, null=False, blank=False)
    content = models.CharField(max_length=300, null=False, blank=False)

class CCC(models.Model):
    aaa = models.ForeignKey(AAA, on_delete=models.CASCADE, null=False, blank=False)
    name = models.CharField(max_length=300, null=False, blank=False)

and I want to order in views.py,

class AAAListCreateView(generics.ListAPIView):
    class AAAPagination(CursorPagination):
        page_size = 2

    queryset = ShortForm.objects.all().annotate(
        b_count=Count("bbb", distinct=True),
        c_count=Count("ccc", distinct=True),
        total=F('b_count')+('c_count')
    )
    serializer_class = AAAListSerializer
    pagination_class = AAAPagination
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_class = AAAListFilterSet
    ordering_fields = ['b_count', 'c_count', 'total']
    ordering = 'b_count'

The problems that I want to ask are…

  1. I want to descending all of my ordering_fields. Descending order without specifying -b_count or -c_count or -total.
  2. In views.py, I annotate all of my ordering_fields. But I think it is not efficient way because it fetches all sorting annotate fields.

What should I do?

LEAVE A COMMENT