1

In the simplified version of my problem I have a model Document that has a manay to many relationship to Tag. I would like to have a query, that given a list of tags will sort the Documents in the order they match the tags i.e. the documents that match more tags will be displayed first and the documents that match fewer tags be displayed later. I know how to do this with a large plain SQL query but i'm having difficulties getting it to work with querysets. Anyone could help?

class Document(model.Model): 
    title = CharField(max_length = 20)
    content = TextField()

class Tag(model.Model):
    display_name = CharField(max_length = 10)
    documents = ManyToManyField(Document, related_name = "tags")

I would like to do something like the following:

documents = Documents.objects.all().order_by(count(tags__in = ["java", "python"]))

and get first the documents that match both "java" and "python", then the documents that match only one of them and finally the documents that don't match any.

Thanks in advance for your help.

karthikr
  • 97,368
  • 26
  • 197
  • 188

1 Answers1

0

Have a look at this : How to sort by annotated Count() in a related model in Django

Some doc :https://docs.djangoproject.com/en/1.6/topics/db/aggregation/#order-by

Community
  • 1
  • 1
maazza
  • 7,016
  • 15
  • 63
  • 96
  • This example and doc helped but in the end I had to do 2 queries. One for ordering the documents that have one or more of the requested tags, the other for the documents that don't have any of the tags. I could not find a way to sort all documents with a single query. – George Octavian Rabanca Aug 22 '13 at 08:19