是否可以使用TastyPie对ToManyField属性中的元素进行排序?

时间:2012-06-15 22:14:48

标签: python django rest tastypie

我有一个使用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

排序

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:4)

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

class BlogPostResource(ModelResource):

    comments = fields.ToManyField("resources.CommentResource",
        attribute=lambda bundle: bundle.obj.comments.all().order_by("published"))

答案 1 :(得分:2)

你也可以尝试在实际的评论模型中添加一个排序(而不是在tastypie Comment ModelResource中):

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

    class Meta:
        ordering = ['published']