Why does Django Queryset say: TypeError: Complex aggregates require an alias?

戏子无情 提交于 2020-12-29 03:35:17

问题


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

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.


回答1:


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')))

Note the latest keyword argument in there. That's the key (I think, again I can't test this).




回答2:


From the django docs:

aggregate() is a terminal clause for a QuerySet that, when invoked, returns a dictionary of name-value pairs

It will automatically provide this value in many generic cases, e.g.

Sum('items') -> sum_items

For your query, it cannot create a default alias, so you must provide one. This is so the query can return a named result for the values produced. All you have to do is give your aggregate a meaningful named alias and all should work fine:

MyModel.objects.all().aggregate(max_created=Max(Func(F('created_ts'), function='UNIX_TIMESTAMP')))


来源:https://stackoverflow.com/questions/32305800/why-does-django-queryset-say-typeerror-complex-aggregates-require-an-alias

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!