How made worked models.Sum() together with models.Count in Django annotations?

103 views
Skip to first unread message

Seti Volkylany

unread,
May 15, 2016, 12:42:44 PM5/15/16
to Django users

For working models.Count() I am using distinct=True. It is right worked if not models.Sum().

next code right worked.

 def get_queryset(self, request):
        qs = super(AnswerAdmin, self).get_queryset(request)
        qs = qs.annotate(
            count_likes=models.Count('likes', distinct=True),
            count_comments=models.Count('comments', distinct=True),
        )
        return qs

I am added new annotation with models.Sum() and found not correct results

    qs = qs.annotate(
        count_likes=models.Count('likes', distinct=True),
        count_comments=models.Count('comments', distinct=True),
        scope=models.Sum(
            models.Case(
                models.When(likes__liked_it=True, then=1),
                models.When(likes__liked_it=False, then=-1),
                output_field=models.IntegerField()
            ),
        ),
    )

Even if I added attribute distinct=True to models.Sum(), it still worked not correct.

How made worked models.Sum() and models.Count() together?

Simon Charette

unread,
May 15, 2016, 7:45:42 PM5/15/16
to Django users
Hi Seti,

As documented this will yield the wrong results in most cases until subqueries
are used instead of JOINs[1].

Cheers,
Simon

[1] https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#combining-multiple-aggregations

Seti Volkylany

unread,
May 16, 2016, 1:31:50 AM5/16/16
to Django users
My new method for resolve problem not working to:
(setattr(i, 'scope', i.get_scope()) for i in qs)
Django not found field 'scope'. (error from traceback)
----------------------------------
Cannot resolve keyword 'scope' into field. Choices are: answers, author, author_id, count_answers, count_opinions, count_tags, date_added, date_modified, id, is_dublicated, opinions, slug, status, tags, text_question, title, views
----------------------------------

понедельник, 16 мая 2016 г., 2:45:42 UTC+3 пользователь Simon Charette написал:
Reply all
Reply to author
Forward
0 new messages