Hi all,
I'm trying to get the ORM to let me sort things based on an annotation, where that annotation requires a subquery to select items to consider.
Concrete example, given models:
class Contact(models.Model):
name = models.CharField()
class Message(models.Model):
sender = models.ForeignKey(Contact, related_name='frm')
recipient = models.ForeignKey(Contact, related_name='to')
unread = models.BooleanField()
send_time = models.DateTimeField(auto_now_add=True)
....
I want to do things like "for Contact X, create a list of other contacts ordered by the number of messages to X" or "Order the contacts by number of unread messages to X"
It seems as if annotate/aggregate should be able to do what I want, but I can't get it to produce a subquery to select the messages to count:
Messages.objects.filter(recipient=X).count() - number of messages to X from all contacts
Contact.objects.annotate(msg_count=Count('frm__id')) - gives number of messages from each contact, but to anyone, not just X
Contact.objects.annotate(msg_count=Count(Q(frm__recipient=X)).order_by('msg_count') - gives the wrong answer for the msg_count (seems to do same as query above)
In SQL, what I want is something like:
But I can't get the ORM to generate SQL that looks like this.
Any pointers/help - even "you can't do that using the ORM" would be very welcome.
Cheers,
Malcolm