【问题标题】:Is it possible to sort elements in a ToManyField attribute using TastyPie?是否可以使用 TastyPie 对 ToManyField 属性中的元素进行排序?
【发布时间】:2012-06-15 22:14:47
【问题描述】:

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

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

有什么办法可以做到吗?

【问题讨论】:

    标签: python django rest tastypie


    【解决方案1】:

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

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

    【讨论】:

    • 如果我这样做,cmets 不会分页
    【解决方案2】:

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

    class Comment(models.Model):
        blog_post = models.ForeignKey(BlogPost, related_name="comments")
        published = models.DateTimeField()
    
        class Meta:
            ordering = ['published']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多