2

I have the following table in Django-1.11:

class Market(models.Model):
    slug = models.SlugField(...)
    active = models.DateTimeField(...)

It would be great if the slug was a foreign key to avoid duplicate values but this is not the case, I am coping with a third party app.

data = [
    {'id': 1, 'slug': 'test-1', 'active': 'datetime.datetime(2017, 9, 18, 10, 43, 8, 581046, tzinfo=<UTC>)'}, 
    {'id': 2, 'slug': 'test-1', 'active': 'datetime.datetime(2017, 9, 20, 10, 43, 8, 581046, tzinfo=<UTC>)'}, 
    {'id': 3, 'slug': 'test-2', 'active': 'datetime.datetime(2017, 9, 10, 10, 43, 8, 581046, tzinfo=<UTC>)'},
    {'id': 4, 'slug': 'test-2', 'active': 'datetime.datetime(2017, 9, 19, 10, 43, 8, 581046, tzinfo=<UTC>)'},
]

I am looking for a query which will return the latest entry with slug test-1 and the latest entry with slug test-2.

Using annotate I just receive the results with their datetime:

Market.objects.values('slug').annotate(Max('active'))
Out[11]: <QuerySet [
{'active__max': datetime.datetime(2017, 9, 18, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-1'},
{'active__max': datetime.datetime(2017, 9, 20, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-1'},
{'active__max': datetime.datetime(2017, 9, 10, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-2'},
{'active__max': datetime.datetime(2017, 9, 19, 10, 43, 8, 581046, tzinfo=<UTC>), 'slug': 'test-2'}
]>

This result does not seem to follow the docs. What am I doing wrong? Is it the SlugField that does not permit "grouping"?

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
raratiru
  • 8,748
  • 4
  • 73
  • 113

1 Answers1

1

looks like you need to add empty order_by() by the default-ordering-or-order-by in the result query can be added extra fields to the group by.

try it:

Market.objects.values('slug').annotate(Max('active')).order_by()
Brown Bear
  • 19,655
  • 10
  • 58
  • 76