【问题标题】:Query to fetch highest rated x with mimimum x people rated查询以获取评分最高的 x,评分最低的 x 人
【发布时间】:2020-04-30 23:50:57
【问题描述】:

模型.py

class Movie(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)
    vote_count = models.IntegerField()

class Watchlist(models.Model):
    userid = models.IntegerField()
    movie_id = models.ForeignKey(Movie, on_delete=models.CASCADE)
    rating = models.IntegerField()

查询以获取评分最高且至少有 5 人评分的电影。

【问题讨论】:

标签: python django django-models django-rest-framework django-views


【解决方案1】:

您应该阅读有关django's annotation. 的基础知识 在你的情况下,这样的事情应该可以工作:

from django.db.models import Count, Sum, F

qs = Movie.objects.annotate(vote_count=Count('watchlist_set'), 
                            vote_sum=Sum('watchlist_set__rating'), 
                            rating = F('vote_sum')/F('vote_count')

    ).filter(
        vote_count__gte=5,
    ).order_by(
        '-rating'
    )

【讨论】:

    猜你喜欢
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    相关资源
    最近更新 更多