How to sort by annotated Count() in a related model in Django
问题 I'm building a food logging database in Django and I've got a query related problem. I've set up my models to include (among other things) a Food model connected to the User model through an M2M-field "consumer" via the Consumption model. The Food model describes food dishes and the Consumption model describes a user's consumption of Food (date, amount, etc). class Food(models.Model): food_name = models.CharField(max_length=30) consumer = models.ManyToManyField("User", through=Consumption)