简体   繁体   中英

Django database: how to apply .annotate() and .aggregate() across all columns?

Suppose I have the following model in django:

class MyModel(models.Model):
    foo = models.CharField(max_length=100)
    bar = models.CharField(max_length=100)

Now I want to find the length of the longest entries for each of the columns in the model.

I can do this for a single field with the following command:

MyModel.objects.annotate(length = Length('foo')).aggregate(Max('length'))

How can I apply this command to all fields (columns) of the table at once in a single command?

You could write like this:

MyModel.objects.aggregate(max_length=Max(Length('foo')))

For all model columns you could find the max length in every row and after aggregate it:

MyModel.objects.annotate(
    row_max_length=Greatest(Length('foo'), Length('bar'))
).aggregate(max_in_model=Max('row_max_length'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM