207👍
You can use the Coalesce
function from django.db.models.functions
like:
answers = (Answer.objects
.filter(<something here>)
.annotate(score=Coalesce(Sum('vote__type'), 0))
.order_by('-score'))
6👍
from django’s documentation for Coalesce:
Prevent an aggregate Sum() from returning None.
The aggregate default argument uses Coalesce() under the hood.
So instead of using Coalesce
, we can use the "default" argument:
answers = Answer.objects.filter(<something here>)
.annotate(score=Sum('vote__type', default=0))
.order_by('-score')
- [Django]-How do I set up Jupyter/IPython Notebook for Django?
- [Django]-Django database query: How to get object by id?
- [Django]-Folder Structure for Python Django-REST-framework and Angularjs
-5👍
What about you use custom Manager
? For example:
AnswerManager(models.Manager):
def all_with_score(self):
qs = self.get_query_set().annotate(score=Sum('vote__type'))
# Here, you can do stuff with QuerySet, for example
# iterate over all Answers and set 'score' to zero if None.
Answer(models.Model):
//some fields here
objects = AnswerManager()
Then, you can use:
>>> answers = Answer.objects.all_with_score().order_by('-score')
- [Django]-Handling race condition in model.save()
- [Django]-Sending post data from angularjs to django as JSON and not as raw content
- [Django]-How to create a fixture file
Source:stackexchange.com