J
J
JRazor2015-11-27 09:24:52
MongoDB
JRazor, 2015-11-27 09:24:52

QuerySet: how to sort by the number of records in the database?

Hello to all toasters!

There was one rather simple question: how to sort the records by the amount in the database when selecting from the database ? (I hasten to note that I'm doing this in Flask and half of the methods from the Django QuerySet documentation do not work)

There are users and they have a "Country" field. I make a selection of countries, but in this case the countries are not sorted.

countries = models.Users.objects.only('country').distinct('country')

What needs to be added for the correct solution? And is it possible to organize the output of the number of records?

Thank you for your attention and replies.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Oscar Django, 2015-11-27
@JRazor

As an option:

from django.db.models import Count
Users.objects.values('country').annotate(num=Count('country')).order_by('-num')

Actually , this might be helpful.

Z
zelsky, 2015-11-27
@zelsky

Clarify the question do you need to alphabetically sort countries by user , or users by country ? In the first case, look for an analogue of templatetags in the second Model.objects.all().filter(country="Russia")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question