If you mean to do aggregation you can use the aggregation features of the ORM:
from django.db.models import Count result = (Members.objects .values('designation') .annotate(dcount=Count('designation')) .order_by() )
This results in a query similar to
SELECT designation, COUNT(designation) AS dcount FROM members GROUP BY designation
and the output would be of the form
[{'designation': 'Salesman', 'dcount': 2}, {'designation': 'Manager', 'dcount': 2}]
If you don’t include the order_by()
, you may get incorrect results if the default sorting is not what you expect.
If you want to include multiple fields in the results, just add them as arguments to values
, for example:
.values('designation', 'first_name', 'last_name')
References:
- Django documentation:
values()
,annotate()
, andCount
- Django documentation: Aggregation, and in particular the section entitled Interaction with default ordering or
order_by()
Related Posts:
- Getting TypeError: __init__() missing 1 required positional argument: ‘on_delete’ when trying to add parent table after child table with entries
- Getting TypeError: __init__() missing 1 required positional argument: ‘on_delete’ when trying to add parent table after child table with entries
- Django 2.1.3 Error: __init__() takes 1 positional argument but 2 were given
- What is a “slug” in Django?
- What does on_delete do on Django models?
- What is the most efficient way to store a list in the Django models?
- __init__() got an unexpected keyword argument ‘user’
- Where does pip install its packages?
- Where does pip install its packages?
- django: TypeError: ‘tuple’ object is not callable
- Can’t fix “zipimport.ZipImportError: can’t decompress data; zlib not available” when I type in “python3.6 get-pip.py”
- No module named ‘psycopg2’
- No module named MySQLdb
- No module named MySQLdb
- How to check Django version
- Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
- is not JSON serializable
- Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty
- Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock
- django:django.core.exceptions.AppRegistryNotReady: Apps aren’t loaded yet
- No module named pkg_resources
- Django upgrading to 1.9 error “AppRegistryNotReady: Apps aren’t loaded yet.”
- Can’t compare naive and aware datetime.now() <= challenge.datetime_end
- django import error – No module named core.management
- Forbidden (403) CSRF verification failed. Request aborted. Even using the {% csrf_token %}
- Can’t connect to local MySQL server through socket ‘/tmp/mysql.sock
- Setting Django up to use MySQL
- django:django.core.exceptions.AppRegistryNotReady: Apps aren’t loaded yet
- OSError – Errno 13 Permission denied
- Pylint “unresolved import” error in Visual Studio Code
- Django – no such table exception
- django MultiValueDictKeyError error, how do I deal with it
- Django – no such table exception
- Is there a list of Pytz Timezones?
- Django – “no module named django.core.management”
- Error: “dictionary update sequence element #0 has length 1; 2 is required” on Django 1.4
- NumPy array is not JSON serializable
- You are trying to add a non-nullable field ‘new_field’ to userprofile without a default
- pip install -r requirements.txt [Errno 2] No such file or directory: ‘requirements.txt’
- super(type, obj): obj must be an instance or subtype of type
- Django Rest Framework — no module named rest_framework
- Error: “dictionary update sequence element #0 has length 1; 2 is required” on Django 1.4
- Python Django: You’re using the staticfiles app without having set the STATIC_ROOT setting
- sqlite3.OperationalError: unable to open database file
- TypeError: int() argument must be a string, a bytes-like object or a number, not ‘list’
- Django reverse lookup of foreign keys
- ImportError: No module named ‘django.core.urlresolvers’
- How to fix error “ERROR: Command errored out with exit status 1: python.” when trying to install django-heroku using pip
- How to set environment variables in PyCharm?
- H14 error in heroku – “no web processes running”
- What does this Django regular expression mean? `?P`
- OperationalError: database is locked
- Is it better to use path() or url() in urls.py for django 2.0?
- TemplateDoesNotExist at /
- No module named django but it is installed
- What is the easiest way to clear a database from the CLI with manage.py in Django?
- Check if an object exists
- Find object in list that has attribute equal to some value (that meets any condition)
- How to check if a user is logged in (how to properly use user.is_authenticated)?
- The view didn’t return an HttpResponse object. It returned None instead
- CSV new-line character seen in unquoted field error
- gunicorn.errors.HaltServer:
django - coercing to Unicode: need string or buffer, NoneType found when rendering in django admin
- coercing to Unicode: need string or buffer, NoneType found when rendering in django admin
- Error loading MySQLdb module: No module named ‘MySQLdb’
- What is related_name used for?
- TypeError: ManyRelatedManager object is not iterable
- Line is too long. Django PEP8
- What does random.sample() method in python do?
- (Python) TypeError: ‘float’ object is not subscriptable
- ‘DataFrame’ object has no attribute ‘sort’
- How to change the font size on a matplotlib plot
- How can I create a dropdown menu from a List in Tkinter?
- How to find all occurrences of a substring?
- Does “\d” in regex mean a digit?
- How to take column-slices of dataframe in pandas
- Python: Get the first character of the first string in a list?
- How to convert string to binary?
- Python error load JSON code of google API
- How do I find the duplicates in a list and create another list with them?
- Get ZeroDivisionError: float division in python
- Remove xticks in a matplotlib plot?
- “for line in…” results in UnicodeDecodeError: ‘utf-8’ codec can’t decode byte
- TypeError: string argument without an encoding
- ValueError: cannot index with vector containing NA / NaN values
- How to append multiple values to a list in Python
- How to multiply all integers inside list
- How can I get the named parameters from a URL using Flask?
- How can I from bs4 import BeautifulSoup?
- Pandas OR statement ending in series contains
- TypeError: Invalid dimensions for image data when plotting array with imshow()
- “getaddrinfo failed”, what does that mean?
- RuntimeWarning: overflow encountered in ubyte_scalars
- Python requests SSL error – certificate verify failed
- How to know/change current directory in Python shell?
- Trying to run Flask app gives “Address already in use”
- What is a unicode string?
- Python a &= b meaning?
- TypeError: can only concatenate tuple (not “int”) in Python
- File “/usr/bin/pip”, line 9, in
from pip import main ImportError: cannot import name main