我正在尝试显示一个显示平均评论率的查询集。 查询看起来很简单 - 尽管Django似乎在生成的group by语句中自动添加了一个额外的字段created_at。有没有办法从group by子句中删除它?是否存在因为模型的META类中定义的默认顺序?
GROUP BY“authentification_antenne”。“name”,“review”。“created_at” 而不只是GROUP BY“authentification_antenne”。“name”
Review.objects.select_related(
'appartement__antenne').values('appartement__antenne__name').annotate(average_rating=Avg('rating')).query
SELECT
"authentification_antenne"."name", AVG("review"."rating") AS "average_rating" FROM "review"
LEFT OUTER JOIN "staffing_appartement" ON ( "review"."appartement_id" = "staffing_appartement"."numero_contrat" )
LEFT OUTER JOIN "authentification_antenne" ON ( "staffing_appartement"."antenne_id" = "authentification_antenne"."id" )
GROUP BY "authentification_antenne"."name", "review"."created_at"
ORDER BY "review"."created_at" DESC
和models.py
class Review(models.Model):
guest = models.ForeignKey(Guest)
comment = models.TextField()
rating = models.IntegerField(null=True)
created_at = models.DateTimeField()
imported_at = models.DateTimeField(auto_now=True)
appartement = models.ForeignKey('staffing.appartement', null=True)
class Meta:
ordering = ['-created_at']
编辑 - 当从模型中删除created_at排序时,我确认生成的语句是正确的。
编辑2 - 我通过在order_by子句中添加我的值来解决此问题,以删除默认过滤
AirbnbReview.objects.select_related('appartement__antenne').values('appartement__antenne__name').order_by('appartement__antenne__name').annotate(average_rating=Avg('rating'))
谢谢