A QuerySet by aggregate field value

后端 未结 3 437
梦如初夏
梦如初夏 2020-11-27 04:02

Let\'s say I have the following model:

class Contest:
    title = models.CharField( max_length = 200 )
    description = models.TextField()

class Image:
            


        
相关标签:
3条回答
  • 2020-11-27 04:17

    The db-level order_by cannot sort queryset by model's python method.

    The solution is to introduce score field to Image model and recalculate it on every Vote update. Some sort of denormalization. When you will can to sort by it.

    0 讨论(0)
  • 2020-11-27 04:20

    You can write your own sort in Python very simply.

    def getScore( anObject ):
        return anObject.score()
    objects= list(Contest.objects.get( pk = id ).image_set)
    objects.sort( key=getScore )
    

    This works nicely because we sorted the list, which we're going to provide to the template.

    0 讨论(0)
  • 2020-11-27 04:21

    Oh, of course I forget about new aggregation support in Django and its annotate functionality.

    So query may look like this:

    Contest.objects.get(pk=id).image_set.annotate(score=Sum('vote__value')).order_by( 'score' )
    
    0 讨论(0)
提交回复
热议问题