Django Queryset为什么说:TypeError:复杂的聚合需要别名? [英] Why does Django Queryset say: TypeError: Complex aggregates require an alias?
本文介绍了Django Queryset为什么说:TypeError:复杂的聚合需要别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Django类,如下所示:
I have a Django class as follows:
class MyModel(models.Model):
my_int = models.IntegerField(null=True, blank=True,)
created_ts = models.DateTimeField(default=datetime.utcnow, editable=False)
运行以下查询集时,出现错误:
When I run the following queryset, I get an error:
>>> from django.db.models import Max, F, Func
>>> MyModel.objects.all().aggregate(Max(Func(F('created_ts'), function='UNIX_TIMESTAMP')))
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "MyVirtualEnv/lib/python2.7/site-packages/django/db/models/query.py", line 297, in aggregate
raise TypeError("Complex aggregates require an alias")
TypeError: Complex aggregates require an alias
如何调整查询集,以免出现此错误?我想找到具有最新created_ts的MyModel实例.而且我想使用 UNIX_TIMESTAMP
函数来获取它.
How do I adjust my queryset so that I don't get this error?
I want to find the instance of MyModel with the latest created_ts. And I want to use the UNIX_TIMESTAMP
function to get it.
推荐答案
我没有运行相同的Django版本,但我认为这会起作用:
I'm not running the same Django version, but I think this'll work:
MyModel.objects.all().aggregate(latest=Max(Func(F('created_ts'), function='UNIX_TIMESTAMP')))
注意其中的 latest
关键字参数.这就是关键(我想,我再也无法测试这一点.)
Note the latest
keyword argument in there. That's the key (I think, again I can't test this).
这篇关于Django Queryset为什么说:TypeError:复杂的聚合需要别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文