G
G
Gregory2020-02-09 15:57:26
Django
Gregory, 2020-02-09 15:57:26

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

Models

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 = 


The result is a list of dictionaries with the name and version. You need model objects or dictionaries with all model fields. How to do it? Make queries for each dictionary? (this doesn't seem like a very reasonable option)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alternativshik, 2020-02-09
@alternativshik

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 question

Ask a Question

731 491 924 answers to any question