我有一个存储一些营销业绩的模型:
class DailyPerformance(models.Model):
class Meta:
unique_together = ('route_hash_value', 'datetime_tz')
ordering = ('-datetime_tz',)
route_hash_value = models.CharField(max_length=255, db_index=True, editable=False)
datetime_tz = models.DateTimeField(db_index=True, editable=False)
network = models.ForeignKey('administration.Network', on_delete=models.PROTECT, null=True)
account = models.ForeignKey('administration.Account', on_delete=models.SET_NULL, null=True)
# Properties
budget = models.FloatField(null=True, db_index=True)
bid = models.FloatField(null=True, db_index=True)
status = models.CharField(max_length=255, null=True, db_index=True)
# METRICS
cost_amount = models.FloatField(null=True, db_index=True)
impressions = models.IntegerField(null=True, db_index=True)
clicks_in = models.IntegerField(null=True, db_index=True)
clicks_out = models.IntegerField(null=True, db_index=True)
revenue_amount_net = models.FloatField(null=True, db_index=True)
_profit = models.FloatField(null=True, db_index=True)
_roi = models.FloatField(null=True, db_index=True)
_ctr = models.FloatField(null=True, db_index=True)
我需要为 drf ModelViewset 生成一个查询集,它聚合数字指标并获取字段的最后一个值:出价、预算和状态。
像这样的东西:
class DailyPerformanceHViewSet(viewsets.ReadOnlyModelViewSet):
def get_queryset(self):
queryset = DailyPerformance.objects.values(
'route_hash_value',
'datetime_tz',
'network',
'account',
).annotate(
cost_amount=Round(Sum('cost_amount'), 3),
revenue_amount_net=Round(Sum('revenue_amount_net'), 3),
impressions=Sum('cost_impressions', output_field=FloatField()),
clicks_in=Sum('cost_clicks_in', output_field=FloatField()),
clicks_out=Sum('cost_clicks_out', output_field=FloatField()),
_profit=Round(Sum('_profit'), 3),
_roi=Round(F('_profit') / F('cost_amount'), 3),
_ctr=Round(F('clicks_out') / F('clicks_in'), 3),
###
budget=..., # <== LATEST BUDGET ORDERED BY -datetime_tz
bid=..., # <== LATEST BID ORDERED BY -datetime_tz
status=..., # <== LATEST STATUS ORDERED BY -datetime_tz
)
return queryset
但我真的不知道该怎么做