Django custom annotation function

前端 未结 2 1234
一生所求
一生所求 2020-12-06 09:31

I want to build a simple hot questions list using Django. I have a function that evaluates \"hotness\" of each question based on some arguments.

Fu

相关标签:
2条回答
  • 2020-12-06 10:25

    For those looking for an updated answer (Django 2.0+) it is possible to subclass Func to generate custom functions for aggregations as per the documentation . There is a good explanation and example here about 80% of the way through the post in the "Extending with custom database functions" section.

    0 讨论(0)
  • 2020-12-06 10:32

    You can't use python functions for annotations. Annotation is a computation that is done on a database level. Django provides you only a set of basic computations which can be processed by the database - SUM, AVERAGE, MIN, MAX and so on... For more complex stuffs only from version 1.8 we have an API for more complex query expressions. Before Django 1.8 the only way to achieve similar functionality was to use .extra which means to write plain SQL.

    So you basically have two and a half options.

    First and a half.

    Write your hotness computation in plain SQL using .extra or via the new API if your Django version is >= 1.8.

    Second.

    Create hotness field inside you model, which will be calculated by a cron job once a day (or more often depending on your needs). And use it for your needs (the hottest list).

    0 讨论(0)
提交回复
热议问题