Reputation: 9523
Hello I have 2 models:
Model User
class User(models.Model):
name = models.CharField(max_length=20, null=True, blank=True)
location = models.ForeignKey(Location, null=True, blank=True, related_name='checkin', on_delete=models.SET_NULL)
Model Location
class Location(models.Model):
name = models.CharField(max_length=100)
How can I order Location by number of checkin of User Model?
I tried this but not success:
Location.objects.annotate(checkin_count=Count('user')).order_by('-checkin_count')
Upvotes: 0
Views: 59
Reputation: 599610
You've got a related_name, you should use that in your annotate call.
Location.objects.annotate(checkin_count=Count('checkin')).order_by('-checkin_count')
Upvotes: 2