Django orm: order post queryset by greatest number of tags from search

I want to order posts by the greatest number of tags a post has

my models:

class post(models.Model):
   description = models.Charfield(max_length = 2000)

class tag(models.Model):
    t = models.Charfield(max_length = 100)

class tags(models.Model):
    tag = models.ForeignKey(tag, ...)
    post = models.ForeignKey(post,...)

I know django's orm supports many to many fields I just make my own table because I feel more comfortable starting out this way.

When inputs a search, example: purple mountain flowers I want to query for posts that have any of the tags and order the query by the posts with the most matching tags. I'm new to using aggregation in django and have no idea how to structure this. Any recommendations?

Firstly you should follow some python/Django standards for naming. Model class should be Titleized (Post, Tag, PostTag) and singular You can use the option through to define your own model for m2m:

class post(models.Model):
    description = models.Charfield(max_length = 2000)
    post_tags = models.ManyToManyField(tag, through=tags)

After that you can make use of django m2m to let you query easier:

from django.db.models import Q, Count
qs = post.objects.annotate(
    num_of_tags=Count('post_tags', filter=Q(post_tags__body__in=search_list)))
).filter(num_of_tags__gt=0).order_by('num_of_tags')
Back to Top