Last active
April 7, 2021 11:59
-
-
Save pawelrubin/519c259274050863249a7dc25087e875 to your computer and use it in GitHub Desktop.
Find the longest length of a field in a Django model.
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
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