Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

python - Django @property used in .aggregate()

I'm trying to aggregate a list of integers from a model. The field that the integers are derived from are an @property decorator field. The decorator works as expected and within the template.html, if passed directly, displays without a problem. If however, I try and pass the @property field through .aggregate() the context passed into the template throws an error that basically says Cannot resolve keyword 'sum_thing' into field. followed by a list of model fields that don't include any of the decorator fields.

My question is - how do you aggregate (Sum) derived fields from the model?

#models.py

class Foo(models.Model):
    a = 10      # a & b are both
    b = 5       # models.IntegerField() items

    @property
    def sum_thing(self):
        return self.a - self.b

#views.py

class Bar(generic.ListView):

    def get_context_data(self, **kwargs):

        qs = Foo.object.all()

        totals = {}

        totals['sumthing'] = qs.aggregate(total=Sum('sum_thing')

        context = {
            'totals': totals
        }

        return context

** I've greatly simplified the models.py and the views.py.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can not aggregate using properties since it does not exist in the db. But, you can annotate your query with the help of Django's F expressions to get the actual value for those fields. See the example below.

from django.db.models import F, Sum

Foo.objects.annotate(sum_a_and_b=F('a') + F('b')).aggregate(total=Sum('sum_a_and_b'))

Also you can do any mathematical operation like / * + - with F, also you can do like this

.annotate(answer=F('a') + F('b') * 2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...