Skip to content

Commit

Permalink
Create longest_value_in_field.md
Browse files Browse the repository at this point in the history
  • Loading branch information
williln authored Feb 28, 2024
1 parent f17bbce commit 4a2da14
Showing 1 changed file with 15 additions and 0 deletions.
15 changes: 15 additions & 0 deletions django/longest_value_in_field.md
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.")
```

0 comments on commit 4a2da14

Please sign in to comment.