我有一个Django类,如下所示:
class MyModel(models.Model):
my_int = models.IntegerField(null=True, blank=True,)
created_ts = models.DateTimeField(default=datetime.utcnow, editable=False)
当我运行以下查询集时,出现错误:
>>> 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
函数来获取它。 最佳答案
我没有运行相同的Django版本,但是我认为这可以工作:
MyModel.objects.all().aggregate(latest=Max(Func(F('created_ts'), function='UNIX_TIMESTAMP')))
注意其中的
latest
关键字参数。这就是关键(我想,我再也无法测试这一点)。关于django - 为什么Django Queryset说: TypeError: Complex aggregates require an alias?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32305800/