【问题标题】:Django - query aggregation by date and avg valueDjango - 按日期和平均值查询聚合
【发布时间】:2019-02-28 22:34:44
【问题描述】:

我有一个应用程序,其中 Gym 与许多 Surveys(多对多)相关联,Survey 与许多 Answers 相关联。

Answer 有一个数字 value,它与 SurveyGym 相关联。

models.py

class DateTimeModel(models.Model):
    creation_date = models.DateTimeField(verbose_name=_('Creation Date'), auto_now_add=True, db_index=True)
    edit_date = models.DateTimeField(verbose_name=_('Last Edit Date'), auto_now=True, db_index=True)
    ...


class Gym(DateTimeModel):
    name = models.CharField(max_length=250)
    ...


class Survey(DateTimeModel):
    text = models.CharField(max_length=500)
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    gyms = models.ManyToManyField(Gym)
    ...


class Answer(DateTimeModel):
    value = models.IntegerField()
    survey = models.ForeignKey(Survey, on_delete=models.CASCADE)
    gym = models.ForeignKey(Gym, on_delete=models.PROTECT)
    ...

我需要按天获取特定健身房的选票分布情况。这很容易通过以下方式完成:

views.py

class VotesDistributionByDayViewSet(APIView):
    @staticmethod
    def get(request, gym_id, survey_id):
        votes_by_date = Answer.objects.filter(gym_id=gym_id, survey_id=survey_id)\
            .annotate(day=TruncDay('creation_date'))\
            .values("day")\
            .annotate(count=Count('gym_id'))\
            .order_by('day')

        return Response({
            'votes_by_gym': votes_by_date,
        })

这将返回以下响应(正确):

{
    "votes_by_gym": [
        {
            "day": "2018-06-11T00:00:00+02:00",
            "count": 15
        },
        {
            "day": "2018-06-12T00:00:00+02:00",
            "count": 6
        },
        {
            "day": "2018-06-13T00:00:00+02:00",
            "count": 17
        },
        {
            "day": "2018-06-14T00:00:00+02:00",
            "count": 12
        },
        ...

现在我需要返回每天所有健身房的平均答案数。我尝试了以下查询:

        avg_votes_by_date = Answer.objects\
            .exclude(gym_id=8) \
            .filter(survey_id=survey_id) \
            .annotate(day=TruncDay('creation_date')) \
            .values("day") \
            .annotate(count_answers=Count('gym_id')) \
            .annotate(count_gym=Count('gym_id', distinct=True)) \
            .order_by('day')

返回以下响应:

"avg_votes_by_date": [
        {
            "day": "2018-06-11T00:00:00+02:00",
            "count_answers": 15,
            "count_gym": 1
        },
        {
            "day": "2018-06-12T00:00:00+02:00",
            "count_answers": 6,
            "count_gym": 1
        },
        {
            "day": "2018-06-13T00:00:00+02:00",
            "count_answers": 17,
            "count_gym": 1
        },
        {
            "day": "2018-06-14T00:00:00+02:00",
            "count_answers": 12,
            "count_gym": 2
        },
        {
            "day": "2018-06-15T00:00:00+02:00",
            "count_answers": 29,
            "count_gym": 2
        },

如何使用count_answers / count_gym 的结果添加第三个键?有没有更好的方法来获得这个平均值?

【问题讨论】:

    标签: django django-rest-framework django-queryset


    【解决方案1】:

    对于第二个查询,我建议您在选定的值中同时注释“count_answers”和“count_gym”,然后用强制转换进行划分:

    avg_votes_by_date = Answer.objects \
        .exclude(gym_id=8) \
        .filter(survey_id=survey_id) \
        .annotate(day=TruncDay('creation_date')) \
        .values('day') \
        .annotate(count_answers=Count('gym_id')) \
        .annotate(count_gym=Count('gym_id', distinct=True)) \
        .annotate(avg=Cast(F('count_answers'), FloatField()) / Cast(F('count_gym'), FloatField())) \
        .order_by('day')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      • 2023-04-04
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      相关资源
      最近更新 更多