-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
15 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
# Finding the longest value of a particular field | ||
|
||
```python | ||
from django.db.models import Max, F | ||
from django.db.models.functions import Length | ||
from myapp.models import MyModel | ||
|
||
# Annotate the queryset with the length of each string in `my_field` | ||
annotated_queryset = MyModel.objects.annotate(my_field_length=Length('my_field')) | ||
|
||
# Aggregate the annotated queryset to find the maximum length | ||
max_length = annotated_queryset.aggregate(max_length=Max('my_field_length'))['max_length'] | ||
|
||
print(f"The longest string in `my_field` is {max_length} characters long.") | ||
``` |