简体   繁体   English

Django根据相关对象对queryset进行排序

[英]Django sort queryset according to related objects

First, happy Chinese new year. 首先,春节快乐。

I got this problem and I am searching for a good way to sort queryset: 我遇到了这个问题,我正在寻找一种对queryset进行排序的好方法:

The are three entities: Service, Order, Rating . 这是三个实体: Service, Order, Rating

A Service object can have many Order objects, an Order object can only have one Rating object. 一个Service对象可以有多个Order对象,一个Order对象只能有一个Rating对象。 Now, I want to rank the a Service according to its average Rating . 现在,我想根据Service的平均RatingService进行排名。

The most straight-forward answer will be: first query all Orders of Service and calculate its average Rating , then sort the Service according to average rating. 最直接的答案是:首先查询所有Service Orders并计算其平均Rating ,然后根据平均评分对Service进行排序。

However, I am worried about the efficiency and responsiveness. 但是,我担心效率和响应速度。

So, I am thinking that there should be an attribute in the Service object: Average_Rating . 因此,我认为Service对象中应该有一个属性: Average_Rating And every time a review is created, the Average_Rating is updated. 每次创建审阅时,都会更新Average_Rating

Is this method a good way to improve responsiveness? 这种方法是提高响应速度的好方法吗? If so, what is the best way to implement it? 如果是这样,实施它的最佳方法是什么? Thank you. 谢谢。

If you don't want to denormalize, you can use annotation . 如果您不想反规范化,则可以使用注释

Assume your models are something like: 假设您的模型如下所示:

class Service(models.Model):
    name = models.CharField(max_length=5)

class Order(models.Model):
    name = models.CharField(max_length=5)
    service = models.ForeignKey(Service)

class Rating(models.Model):
    order = models.OneToOneField('Order')
    grade = models.IntegerField()

Then you can annotate and query by the average: 然后,您可以按平均值进行注释和查询:

Service.objects.annotate(avg_rate=Avg('order__rating__grade')).order_by('avg_rate')

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

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