Answer the question
In order to leave comments, you need to log in
How to get model objects after grouping Django ORM?
I need to group directories by name and select the directory with the latest version from each group. I do it like this:
Handbook.objects.values('name').annotate(latest_version=Max('version'))
class Handbook(models.Model):
name = models.CharField(max_length=128)
short_name = models.CharField(max_length=32)
description = models.CharField(max_length=255)
version = models.CharField(max_length=16, blank=False)
create_date = models.DateTimeField('date created', default=timezone.now)
def __str__(self):
return self.name
class Meta:
unique_together =
Answer the question
In order to leave comments, you need to log in
It is not clear what model fields should be if there can be different data, and only the name and version are unique. Version is generally a string and how to find Max() there is also unclear
For example -
name = foo
short_name = foo_1
description = 'Foo description'
version = v1
the second object will be with
name = foo
short_name = foo_1_1
description = 'Foo description 1'
version = v2
After grouping will be {"name": "foo", "version": v2} and which short_name and description should be taken in this case?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question