我使用的是Django和python3.7。我想在较大查询的条件中包含子查询。
from django.db.models.functions import ExtractHour
...
hour_filter = ExtractHour(ExpressionWrapper(
F("article__created_on") + timedelta(0, avg_fp_time_in_seconds),
output_field=models.DateTimeField()
),
)
query = StatByHour.objects.filter(hour_of_day=OuterRef(hour_filter))
...
包含它的更大的查询是
^{pr2}$但是,当我运行这个时,我得到了错误
'ExtractHour' object has no attribute 'split'
这意味着什么?我如何调整我的过滤器,使这个错误消失?
编辑:添加生成外部查询的对象的模型。。。
class ArticleStat(models.Model):
objects = ArticleStatManager()
article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='articlestats')
...
votes = models.FloatField(default=0, null=False)
正如@WillemVanOnsem所指出的:
然后你做到了:
其中
^{pr2}$hour_filter
被视为字段查找,Django正在执行一种以收集预期字段查找的部分。在
但是
hour_filter
在这里是一个ExtractHour
,因此出现了错误。在您可以尝试用所需的小时对文章统计信息进行注释,然后处理结果:
整个过程可能看起来像(我没有测试过这个,只是为了给你指出正确的方向):
附录:
如果仍要在此处使用子查询,可以修改已有的子查询,使其在带注释的字段上工作:
祝你好运!在
OuterRef
用于从父查询获取一个值,但是这里您根本不需要外部查询的引用。在所以这里不需要} 所说:
OuterRef
。正如documentation on ^{在
ExtractHour
内使用OuterRef
:相关问题 更多 >
编程相关推荐