如何在Django相关模型中排序顺序(通用关系)

时间:2010-02-28 17:28:39

标签: django django-models django-forms django-views

我的模特:

隐私权|发布广告:

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中的项目进行排序?我该怎么办?

2 个答案:

答案 0 :(得分:2)

我认为这应该有效:

items = Item.objects.annotate(hits=Sum('hitcounter__hits')).order_by('-hits')

Django聚合的文档here

答案 1 :(得分:0)

如果您希望默认使用此排序,那么元选项order_with_respect_toordering可能会有所帮助。

您的模型将如下所示:

class HitCounter:
    # properties here

    class Meta:
        order_with_respect_to: 'content_object'  # not sure if this really works
        ordering: ['-hits']