【问题标题】:How to sort order in Django Related Models (Generic relations)如何在 Django 相关模型中排序(通用关系)
【发布时间】:2010-02-28 17:28:38
【问题描述】:

我的模型:

HitCounter:

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

【问题讨论】:

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


    【解决方案1】:

    我认为这应该可行:

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

    Django 聚合文档here

    【讨论】:

    • 您的第一个模型是否名为“HitCounter”并且您仍然遇到异常?可以留言吗?
    • 我已经获取了项目 id 的有序列表。但是如何使用它从 Item 对象中获取项目。我用过for循环,但看起来不太好。
    • 对不起,我不明白你的意思。能改一下吗?
    • 我在这里提出了一个问题:stackoverflow.com/questions/2364905/…。请访问并获取您的积分。谢谢!
    【解决方案2】:

    如果您希望默认进行此排序,元选项 order_with_respect_toordering 可能会有所帮助。

    您的模型将如下所示:

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

    【讨论】:

    • django.db.models.fields.FieldDoesNotExist:HitCounter(或其他)没有名为“content_object”的字段
    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 2016-09-22
    • 2015-02-06
    • 1970-01-01
    • 2010-11-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多