1👍
✅
You can use Django’s annotate() method to add a computed field to each BigTextKeyword object that represents the frequency count of its associated BigText. Then, you can use the order_by() method to sort the queryset in descending order based on this computed field.
Here’s an example:
from django.db.models import Count
class BigTextKeywordViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
queryset = BigTextKeyword.objects.all()
serializer_class = BigTextKeywordSerializer
def get_queryset(self):
keyword_filter = Q()
search_content = self.request.query_params.get('search_content', '')
for term in search_content.split(' '):
keyword_filter |= Q(keyword__icontains=term)
keywords = Keyword.objects.filter(keyword_filter)
# Use annotate to add a computed field for the frequency count of each BigText
result = self.queryset.filter(keyword__in=keywords).annotate(
bigtext_count=Count('bigtext')
)
# Order the results based on the frequency count in descending order
result = result.order_by('-bigtext_count')
return result
Source:stackexchange.com