2012-06-15 63 views
2

我有一個使用Django Tastypie的REST API。考慮下面的代碼是否可以使用TastyPie對ToManyField屬性中的元素進行排序?

該機型

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

我設法在BlogPostResource更改字段下面來解決這個問題:

class BlogPostResource(ModelResource): 

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

如果我這樣做,評論不分頁 – rolnn

2

您也可以嘗試在實際的評論模型添加排序(不是在tastypie評論ModelResource):

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

    class Meta: 
     ordering = ['published'] 
相關問題