在Django中排序内部GenericRelation字段

时间:2013-03-25 09:12:47

标签: django

我有一个模型项目:

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)

在我的模板中我有类似的东西,我在模板中设置了项目作为Item.objects.all():

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

我真正想要的是,每个项目的注释都将按created_date排序。如何设置内部genericRelation的排序方式?

1 个答案:

答案 0 :(得分: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