Using model methods in aggregates Using model methods in aggregates django django

Using model methods in aggregates


You've got quite a difficult setup, it might be easier to have the HDSVunits mapping on the Price model to make it easier to access in queries.

The best I can come up with is something like this:

Booking.objects.aggregate(    hdsv=(        Sum('classnumbers__numberofstudents') *         Case(            When(price__name='Full-Day', then=2.0),            When(price__name='Half-Day AM', then=1.0),            When(price__name='Full-Day PM', then=1.0),            When(price__name='Three-Quarter Day', then=1.5),            When(price__name='1 Hour', then=0.5),            When(price__name='Custom', then=1.0),            output_field=FloatField(),        )    ))

If the HDSV value were stored as a field on the Price model, you could simply do:

Booking.objects.aggregate(    hdsv=Sum('classnumbers__numberofstudents') * F('price__hdsv'))

On a side note, you should really consider following the Python naming convensions which would make it easier for other Python developers to help you.


If the data that getHDSV is returning is not from the database then aggregate and annotate will not be able to be used to gather statistics on it.