Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 397
Saqib Ali Avatar asked Aug 31 '15 07:08

Saqib Ali


1 Answers

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

like image 178
Exelian Avatar answered Sep 28 '22 03:09

Exelian