From 4a2da14df4a5d7f05692da22d74d7a6c42a904d7 Mon Sep 17 00:00:00 2001 From: Lacey Henschel Date: Wed, 28 Feb 2024 11:19:30 -0800 Subject: [PATCH] Create longest_value_in_field.md --- django/longest_value_in_field.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 django/longest_value_in_field.md diff --git a/django/longest_value_in_field.md b/django/longest_value_in_field.md new file mode 100644 index 0000000..9628f40 --- /dev/null +++ b/django/longest_value_in_field.md @@ -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.") +```