Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

python - Collect ids as list during annotate grouping by different parameters in Django

I have to collect distinct vehicle_type_ids while annotating in django .

This is what I have right now along with grouping by city_code and final_driver_owner_contact. I wish to collect all corresponding vehicle_types grouped by them (city_code, final_driver_owner_contact) and month.

od_engagement = list(FieldOpsBooking.objects.using(
    'analytics').exclude(**exclude_query).filter(**filter_query).values(
    'city_code', 'final_driver_owner_contact').annotate(
    booking_count=Count('final_driver_owner_contact'),
    vehicle_count=Count('final_driver_vehicle_no', distinct=True),
    total_cost=Sum('final_driver_rate'),
    month=TruncMonth('pick_up_at')))

Is it possible to add it to this query (similar to mongodb which lets you push ids while grouping in aggregate.

Or is there another way to get the same using a separate query.

Any help is appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since I have been using postgresql alongside Django . This worked for me without the distinct part.

There are plenty of articles on Group Concat, haven't found anything to work.

Here is the solution only for Postgres

Using StringAgg('vehicle_type_id', ',')

from django.contrib.postgres.aggregates import StringAgg

od_engagement = list(FieldOpsBooking.objects.using(
    'analytics').exclude(**exclude_query).filter(**filter_query).values(
    'city_code', 'final_driver_owner_contact').annotate(
    vehicle_types = StringAgg('vehicle_type_id', ','),
    booking_count=Count('final_driver_owner_contact'),
    vehicle_count=Count('final_driver_vehicle_no', distinct=True),
    total_cost=Sum('final_driver_rate'),
    month=TruncMonth('pick_up_at')))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...