Sunday, May 15, 2016

How to create new field in queryset instead of usign annotation?

Next code not working right

    def get_queryset(self, request):
        qs = super(QuestionAdmin, self).get_queryset(request)
        qs = qs.annotate(
            count_answers=models.Count('answers', distinct=True),
            count_tags=models.Count('tags', distinct=True),
            count_opinions=models.Count('opinions', distinct=True),
            scope=models.Sum(
                models.Case(
                    models.When(opinions__is_useful=True, then=1),
                    models.When(opinions__is_useful=False, then=-1),
                    output_field=models.IntegerField()
                ), distinct=True
            ),
        )
        return qs

I am tried made new field manually as:

    def get_queryset(self, request):
        qs = super(QuestionAdmin, self).get_queryset(request)
        qs = qs.annotate(
            count_answers=models.Count('answers', distinct=True),
            count_tags=models.Count('tags', distinct=True),
            count_opinions=models.Count('opinions', distinct=True),
        )
        (setattr(i, 'scope', i.get_scope()) for i in qs)
        return qs

But Django not visible my new field (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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/d318e940-7be9-48c9-a736-751ff29dd4ad%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment