Search code examples
pythondjangoresttastypie

Is it possible to sort elements in a ToManyField attribute using TastyPie?


I have a REST API using Django Tastypie. Given the following code

The models

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

The resources

class CommentResource:
    # omitted

class BlogPostResource(ModelResource):

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

When I ask for a blogpost I get something like:

GET: api/blogpost/4/

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

However, the comments are not necessarily sorted by any field. I would like to make sure they are sorted by a specific key (published)

Is there any way to achieve this?


Solution

  • I managed to solve the issue by changing the field in BlogPostResource to the following:

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