2

我有一个使用 Django Tastypie 的 REST API。给定以下代码

模型

class BlogPost(models.Model):
    # class body omitted, it has a content and an author


class Comment(models.Model):
    blog_post = models.ForeignKey(BlogPost, related_name="comments")
    published = models.DateTimeField()
    # rest of class omitted

资源

class CommentResource:
    # omitted

class BlogPostResource(ModelResource):

    comments = fields.ToManyField("resources.CommentResource",
        attribute="comments")

当我要求一篇博文时,我得到了类似的信息:

GET: api/blogpost/4/

{
   'content' : "....",
   'author' : "....",
   'comments' : ['api/comment/4/', 'api/comment/5']
}

但是,评论不一定按任何字段排序。我想确保它们按特定键(published)排序

有什么办法可以做到这一点?

4

2 回答 2

4

我设法通过将字段更改BlogPostResource为以下内容来解决问题:

class BlogPostResource(ModelResource):

    comments = fields.ToManyField("resources.CommentResource",
        attribute=lambda bundle: bundle.obj.comments.all().order_by("published"))
于 2012-06-15T22:32:57.843 回答
2

您也可以尝试在实际的评论模型中添加排序(而不是在美味的评论模型资源中):

class Comment(models.Model):
    blog_post = models.ForeignKey(BlogPost, related_name="comments")
    published = models.DateTimeField()

    class Meta:
        ordering = ['published']
于 2013-06-30T00:28:19.730 回答