Recommand · June 14, 2021 0

Django rest framework group objects by date

I have a Django model like below:

from django.models import Model


class Post(models.Model):
    headline = models.CharField(max_length=100)
    content = models.TextField()
    published_at = models.DateField()

Requirement is to make API that group post objects by publish date (daily) and with pagination. Expected response is:

{
  "publish_date": "2020-05-03",
  "posts": [
    {
      "id": 1,
      "headline": "headline1",
      "content": "post body"
    },
    ...
  ],
  "publish_date": "2020-05-16",
  "posts": [
    {
      "id": 4,
      "headline": "headline2",
      "content": "post body"
    },
    ...
  ],
  ...
}

How to make this done efficiently with Django? I don’t want to iterate over dates and filter posts by that date. I tried queryset’s dates and annotate methods with no successful result:

from django.db.models import Subquery, OuterRef

from blog.models import Post

post_subquery = Post.objects.filter(published_at=OuterRef('published_at')).values('published_at')
Post.objects.dates('published_at', 'day').annotate(publish_day=F('published_at'), posts=Subquery(post_subquery)).values('publish_day', 'posts')

It says Cannot resolve keyword 'publish_day' into field.

How should I do this via Django’s ORM?