Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

Django order by number of related objects in class Meta

$
0
0

In Django, i want to set the default model ordering to be by the number of related objects. In my case i would like to order the objects by the number of likes, where likes is a ManyToManyField of users that have liked the post:

class Post(models.Model):    likes = models.ManyToManyField(User)    class Meta:        ordering = []  # What can i put here?

The common solution seems to be django aggregation:

from django.db.models import Counttop_posts = Post.objects.annotate(num_likes=Count('likes')).order_by('-num_likes')

But this is called on the queryset, and doesn't seem like an option when defining the model.


Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>