简体   繁体   English

Django:如何连接和注释多个SQL表?

[英]Django: how to join and annotate multiple sql tables?

I'm building a sample django app and I can't aggregate properly some sql results. 我正在构建一个示例django应用程序,并且无法正确聚合一些sql结果。

Consider these 3 models: 考虑以下三种模型:

Movie model 电影模特

class Movie(models.Model):
    source_id = models.CharField(max_length=100, primary_key=True)
    title = models.CharField(max_length=200, validators=[MinLengthValidator(1)])

Rating model 评分模型

class Rating(models.Model):
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    rating = models.PositiveIntegerField()
    username = models.CharField(max_length=100, validators=[MinLengthValidator(1)])

Comment model 评论模型

class Comment(models.Model):
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    username = models.CharField(max_length=100, validators=[MinLengthValidator(1)])
    body = models.TextField()

Then consider the following mysql tables: 然后考虑以下mysql表:

movie 电影

+-----------+-----------+
| source_id |   title   |
+-----------+-----------+
| 15sdfsd4  | Spiderman |
+-----------+-----------+

rating 评分

+----+--------+----------+----------+
| id | rating | username | movie_id |
+----+--------+----------+----------+
|  1 |      4 | jack     | 15sdfsd4 |
|  2 |      3 | mick     | 15sdfsd4 |
+----+--------+----------+----------+

comment 评论

+----+----------+--------------------+----------+
| id | username |        body        | movie_id |
+----+----------+--------------------+----------+
|  1 | charles  | I loved this movie | 15sdfsd4 |
|  2 | mick     | Nice sound fx      | 15sdfsd4 |
+----+----------+--------------------+----------+

I would like to query for a list of movie ids and get a summary of the avg rating and the nr of comments. 我想查询电影ID的列表,并获取平均评级和评论的nr的摘要。

I tried something like 我尝试了类似的东西

ids = ['15sdfsd4','54fdf5d']
m = Movie.objects.filter(source_id__in=ids).annotate(Avg('rating'), Count('comment'))

I would expect a comment count of 2 and an avg rating of 3.5 for the movie with id 15sdfsd4 . 我希望ID为15sdfsd4的电影的评论计数为2,平均评级为3.5。 Instead I get a comment count of 4 and an avg rating of 1.5 which I can't make much sense of... 取而代之的是,我得到4的评论数和1.5的平均评分,这对我来说意义不大...

Do you have any suggestion? 你有什么建议吗? Thanks 谢谢

There are two thing that are wrong with following solution 以下解决方案有两件事是错误的

  • You are not specifying column to average on ( rating_rating ) 您未指定要在(rating_rating)上求平均值的列
  • Django combining multiple annotations bug and thread Django结合了多个注释错误线程

Considering count aggregate has distinct and average with duplicates is same this would probably work 考虑到计数总和具有重复且平均值相同,这可能会起作用

 m = Movie.objects.filter(source_id__in=ids).annotate(
     Avg('rating__rating'), 
     Count('comment',distinct=True)
 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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