0

我有一个模型项目:

class Item(models.Model):
    comments = generic.GenericRelation(Comment)
    ...

我的评论模型:

class Comment(models.Model):
    """
    Comment object for any model which want to integrate with the comment engine
    """
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
    comment = models.TextField(max_length=512)
    user = models.ForeignKey( User )
    created_date = models.DateTimeField(auto_now_add=True)

在我的模板中,我有类似的东西,我在模板上下文中将 Items 设置为 Item.objects.all():

{% for item in Items %} 
     {%for comment in item.comments.all %}
          <p> comment.comment</p>
     {%endfor%}
{%endfor%}

我真正想要的是评论将按每个项目的 created_date 排序。如何设置如何对内部 genericRelation 进行排序?

4

1 回答 1

2

使用模型的元类

class Comment(models.Model):
    # attrs
    class Meta:
        ordering = ['created_date']

或使用在您的情况下稍微冗长的经理

class CommentManager(models.Manager):
    def get_queryset(self):
        return super(CommentManager, self).get_queryset().order_by('created_date')


class Comment(models.Model):
    # attrs
    objects = CommentManager()

有关跨关系经理的更多信息: https ://docs.djangoproject.com/en/dev/topics/db/managers/#controlling-automatic-manager-types

于 2013-03-25T09:18:29.647 回答