Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django QuerySet: additional field for counting value's occurence

I have a QuerySet object with 100 items, for each of them I need to know how many times a particular contract_number occurs in the contract_number field.

Example of expected output:

[{'contract_number': 123, 'contract_count': 2}, {'contract_number': 456, 'contract_count': 1} ...]

This means that value 123 occurs 2 times for the whole contract_number field.

Important thing: I cannot reduce the amount of items, so grouping won't work here.

The SQL equivalent for this would be an additional field contract_count as below:

 SELECT *,
 (SELECT count(contract_number) FROM table where t.contract_number = contract_number) as contract_count
FROM table as t

The question is how to do it with a Python object. After some research, I have found out that for more complex queries the Queryset extra method should be used. Below is one of my tries, but the result is not what I have expected

    queryset = Tracker.objects.extra(
    select={
        'contract_count': '''
        SELECT COUNT(*)
        FROM table
        WHERE contract_number = %s
        '''
    },select_params=(F('contract_number'),),)

My models.py:

class Tracker(models.Model):
    contract_number = models.IntegerField()

EDIT: The solution to my problem was Subquery()

like image 269
Supergator Avatar asked Nov 15 '25 05:11

Supergator


1 Answers

You can use annotation like this:

from django.db.models import Count
Tracker.objects.values('contract_number').annotate(contract_count=Count('contract_number')).order_by()
like image 94
neverwalkaloner Avatar answered Nov 17 '25 19:11

neverwalkaloner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!