Django Queryset 根据另一个字段的排序创建 .values()
我正在尝试数据点最有可能的预测类别。因为代码是最好的解释:
模型:
class DataPoint(models.Model):
#... unimportant fields
class PredResult(models.Model):
likelihood = models.FloatField()
value = models.IntegerField()
data_point = models.ForeignKey(DataPoint)
对于每个 DataPoint 对象,我试图找到可能性最高的 PredResult 的值。目前我正在使用 for 循环:
data_points = DataPoints.objects.select_related('predresult')
for dp in data_points:
if dp.predresult_set.all().exists():
val = dp.predresult_set.order_by('-likelihood')[0].value
#do other stuff here with val and dp
我想将 best_value
字段添加到 DataPoint
查询集中。目前,每个数据点大约有 5 个 PredResult 对象,大约有 20,000 个数据点(尽管这可能会迅速膨胀)。然而,这个 for 循环在视图中完成需要很长时间。
谁能建议一种方法来处理这个问题?要么是 Django ORM 技巧,要么是 Queryset
上的 extra()
方法。或者您认为我应该在 PredResult
对象上使用 post-save
方法并直接更新 DataPoint
对象上的字段?
如果需要,我使用 MySQL 作为数据库后端。
I'm trying to the most likely predicted category for a datapoint. Since code is the best explanation:
models:
class DataPoint(models.Model):
#... unimportant fields
class PredResult(models.Model):
likelihood = models.FloatField()
value = models.IntegerField()
data_point = models.ForeignKey(DataPoint)
For each DataPoint object I am trying to find the value
for the PredResult with the highest likelihood. Currently I'm using a for-loop:
data_points = DataPoints.objects.select_related('predresult')
for dp in data_points:
if dp.predresult_set.all().exists():
val = dp.predresult_set.order_by('-likelihood')[0].value
#do other stuff here with val and dp
I'd like to get add a best_value
field to the DataPoint
queryset. Currently there are ~5 PredResult objects per DataPoint and ~20,000 DataPoints (although this may balloon rapidly). However, this for-loop takes too long to complete within a view.
Can anyone suggest a way to deal with this? Either a Django ORM trick, a extra()
method on the Queryset
. Or do you think I should use a post-save
method on the PredResult
object and update a field on the DataPoint
object directly?
If its needed I'm using MySQL as the database backend.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
聚合:
现在
values
中的每个元素都有一个max_result
属性,其中包含最大相关结果。Aggregation:
Now each element in
values
has amax_result
attribute containing the max related result.