[Django]-Get distinct django objects from queryset sorted by latest

5๐Ÿ‘

โœ…

I was able to get this to work using the following:

blog_ids = Blog.objects.filter(is_published = True)\
.order_by('author_id', '-published_date')\
.distinct('author_id')\
.values('id', flat=True)

blog_list = Blog.objects.filter(id__in=blog_ids)\
.order_by('-published_date')

Which gets exactly what I wanted!!!!

More detail on this method can be found here: https://stackoverflow.com/a/32760239/2990550

๐Ÿ‘คMegawatt

1๐Ÿ‘

You can read this post in official Djang documentation.
Based on this post, when you specify field names in distinct clause, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order. To get the goal you said above, following this :

from django.db.models import Max
blog_list = Blog.objects.filter(is_published=True).values('author').annotate(Max('published_date'))

0๐Ÿ‘

Try this solution

blog_list = Blog.objects.filter(is_published=True).distinct('author').order_by('-published_date', 'author')

0๐Ÿ‘

I think you should try this:

Blog.objects.filter(is_published=True).order_by('-published_date').order_by('author').distinct('author')

It will give what you want.
here you will get all authors latest blogs.

๐Ÿ‘คAshish

0๐Ÿ‘

Try this code
Now this is remove null values

from django.db.models import Max

Blog.objects.filter(pk__in=Blog.objects.order_by('-published_date').values(
        'author_id').annotate(max_id=Max('pk')).values('max_id'),
                        is_published=True, author_id__isnull=False).order_by('-author_id')
๐Ÿ‘คGorkhali Khadka

Leave a comment