[Answer]-How to speed up sorting of django queryset?

1👍

Lets say we have an incoming user named as u for which we want to show suggestions, then the query would be:

from django.db.models import Count

interests_ids = u.interests.values_list('id', flat=True) # select ids of incoming user interests
suggestions = User.objects
                  .exclude(id=u.id) # exclude current user
                  .filter(is_verified=True) # filter only verified users
                  .filter(interests__id__in=interests_ids) # select users based on common interests
                  .annotate(interests_count=Count('interests')) # count numbers of interests for each user after filtering
                  .order_by('-interests_count') # order users by max common interests

The suggestions queryset will not contain any user which don’t share any common interest with user u. If you still want to show some suggestions if there are no suggestions from above query, then you can filter User based on some other criteria e.g. users living in same country or city.

Leave a comment