[Answered ]-How to get the Primary key of annotate Count

1👍

You can get the smallest (or largest) item with a Min [Django-doc] (or Max) aggregate:

from django.db.models import Min

dup_job = Order.objects.filter(
    orderpickup__pickup_date__range=(start_date, end_date)
).values(
    'orderdelivery__delivery_address',
    'orderpickup__pickup_date',
).annotate(
    min_id_order=Min('id_order')
    duplicated=Count('orderdelivery__delivery_address')
).filter(
    duplicated__gt=1
)

or for , you can make use of the ArrayAgg [Django-doc] to generate a list:

# PostgreSQL only

from django.contrib.postgres.aggregates import ArrayAgg

dup_job = Order.objects.filter(
    orderpickup__pickup_date__range=(start_date, end_date)
).values(
    'orderdelivery__delivery_address',
    'orderpickup__pickup_date',
).annotate(
    min_id_order=ArrayAgg('id_order')
    duplicated=Count('orderdelivery__delivery_address')
).filter(
    duplicated__gt=1
)

Leave a comment