0

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?

nicat9507
  • 39
  • 9
  • 2
    can you not just use order_by('published_at') ? seems like it would achieve your goal – Henty Jun 11 '21 at 08:47
  • how it achieves my goal? it will return queryset than contains single `post` instances. I need the grouped by daily. – nicat9507 Jun 11 '21 at 09:14
  • @nicat9507 [This](https://stackoverflow.com/questions/629551/how-to-query-as-group-by-in-django) may help your for a better understanding and solve your problem. – Klim Bim Jun 11 '21 at 09:34
  • https://stackoverflow.com/questions/64995344/django-rest-serialize-field-group-by-date – Ebrahim Abdollahian Oct 26 '22 at 06:25

0 Answers0