Django ORM通过IN

时间:2018-09-23 10:34:21

标签: python django django-orm

型号:

class Rating(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, verbose_name='Post')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name='User')
    rating = models.IntegerField(verbose_name='Rating')
    date = models.DateTimeField(auto_now_add=True, verbose_name='add date', blank=True, null=True)
    class Meta:
        db_table = 'rating'
        ordering = ['-id']

基于此模型,需要对此查询进行模拟

查询:

select post_id, AVG(rating) from rating where post_id in (1,2,3,4,5,6)
group by post_id order by post_id

尝试这样做:

Rating.objects.values('post_id').filter(post_id__in=post_ids).annotate(avg_rating=Avg('rating'))

但是最后查询看起来像这样,并在id字段上分组:

SELECT `rating`.`post_id`, AVG(`rating`.`rating`) AS `avg_rating` FROM `rating` WHERE `rating`.`post_id` IN (1,2,3,4,5,6) GROUP BY `rating`.`id` ORDER BY `rating`.`id` DESC

如何仅对post_id字段进行分组?

1 个答案:

答案 0 :(得分:1)

使用

覆盖默认顺序(ordering = ['-id']
...order_by('post_id', )