简体   繁体   中英

Django Aggregation with a Model that has two foreign key fields pointing to same foreign Model?

I have this model:

from reviews.models import *
from django.db.models import Count

class Review(models.Model):
    user = models.ForeignKey('core.User')
    status = models.CharField(default='5 star', max_length=100)
    reviewed_date = models.DateField(default=datetime.date.today, blank=True, null=True)
    reviewer = models.ForeignKey('core.User', related_name='reviewer', null=True)

I can list the top 5 Review.user's with the most Reviews like this:

for u in User.objects.annotate(num_reviews=Count('review')).order_by('-num_reviews')[:5]:
...    print u.login, u.num_reviews, u.title
...    
bobby 395 Manager
paul 377 Project Manager
micheal 283 Program Manager
kim 252 Engineer
goober 210 Engineer

But how can I list the top 5 Review.reviewers?

In your case it's

for u in User.objects.annotate(num_reviews=Count('reviewer')).order_by('-num_reviews')[:5]:
...    print u.login, u.num_reviews, u.title

I think the problem here is with related name reviewer which confused you. It should have named like reviewed_reviews which is more clear and understandable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM