Skip to content

Instantly share code, notes, and snippets.

@pawelrubin
Last active April 7, 2021 11:59
Show Gist options
  • Save pawelrubin/519c259274050863249a7dc25087e875 to your computer and use it in GitHub Desktop.
Save pawelrubin/519c259274050863249a7dc25087e875 to your computer and use it in GitHub Desktop.
Find the longest length of a field in a Django model.
from django.db.models import Model, Q
from django.db.models.functions import Length
def max_length(field: str, model: Model) -> int:
return getattr(
model.objects.filter(~Q(**{field: None}))
.annotate(**{f"{field}_length": Length(field)})
.order_by(f"{field}_length")
.last(),
f"{field}_length",
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment