1👍
✅
You can accomplish that by using annotations:
from django.db.models import Count
MyModel.objects.annotate(num_users=Count('watchers')).order_by('num_users')
1👍
The problem is that django-notification uses generic foreign keys.
So I’ve redefined my watchers field:
watchers = generic.GenericRelation(notification.ObservedItem)
Then I can get all the watchers for a specific instance of MyModel.
$x = MyModel.objects.get(id=1)
$x.watchers.all()
$[<ObservedItem: ObservedItem object>, <ObservedItem: ObservedItem object>, <ObservedItem: ObservedItem object>]
$x.watchers.count()
$3
Close but no cigar. I wanted to do was something like this:
MyModel.objects.annotate(count=Count('watchers')).order_by('count')
Which is something that Django can’t do, according to the docs.
Django’s database aggregation API doesn’t work with a GenericRelation.
Not to worry, I think this will probably help:
http://charlesleifer.com/blog/generating-aggregate-data-across-generic-relations/
Repo is here:
https://github.com/coleifer/django-generic-aggregation
I’ve not tried it out yet…
- [Answered ]-AttributeError: 'WSGIRequest' object has no attribute 'getlist'
- [Answered ]-AttributeError: 'NoneType' object has no attribute '_consistency' when trying to show a list from database
- [Answered ]-JSON field postgress like
Source:stackexchange.com