我的模特:
隐私权|发布广告:
hits = models.PositiveIntegerField(default=0)
object_pk = models.TextField('object ID')
content_type = models.ForeignKey(ContentType,
verbose_name="content cype",
related_name="content_type_set_for_%(class)s",)
content_object = generic.GenericForeignKey('content_type', 'object_pk')
档案:
title = models.CharField(_('Title'), max_length=400)
desc = models.TextField(_('Description'), blank=True
)
我想按HitCounter中的点击顺序对Item中的项目进行排序?我该怎么办?
答案 0 :(得分:2)
我认为这应该有效:
items = Item.objects.annotate(hits=Sum('hitcounter__hits')).order_by('-hits')
Django聚合的文档here
答案 1 :(得分:0)
如果您希望默认使用此排序,那么元选项order_with_respect_to
和ordering
可能会有所帮助。
您的模型将如下所示:
class HitCounter:
# properties here
class Meta:
order_with_respect_to: 'content_object' # not sure if this really works
ordering: ['-hits']