Django, get number of items from each author, return authors with most items

StackOverflow https://stackoverflow.com/questions/22353987

  •  13-06-2023
  •  | 
  •  

سؤال

I have following models:

#models.py
class Blog(models.Model):
    author = models.ForeignKey(MyUser)

#author
class MyUser(AbstractUser):
    picture = models.ImageField()

I want to find out which authors have the most posts and get the top 6 in the most optimum way possible. I also want to get the picture from each author.

This is what I have, but I can't figure how to get the profile pic in the same query. Can anyone help please? Thanks,

authors = Blog.objects.values('author').annotate(posts=Count('author')).order_by('-posts')[:6]
هل كانت مفيدة؟

المحلول

The bellow queryset should do the job:

authors = Blog.objects.values('author__picture').annotate(posts=Count('author')).order_by('-posts')[:6]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top