Created
April 5, 2022 12:32
-
-
Save stuaxo/ed770677426ab807cbbb4b452ad2c689 to your computer and use it in GitHub Desktop.
Django concatenate non null fields. #snippet
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
# Ended up not using this, as there was only one place in the codebase. | |
def concat_non_null_fields(fields, seperator): | |
""" | |
Build a case statement expression to concatenate the supplied fields where isnull is False. | |
:param fields: List of fields to concatenate. | |
:param seperator: Seperator to use between fields. | |
:return: Case statement expression. | |
Loops through each field and adds a case statement that adds the field if present, along | |
with a seperator, if not then an empty string is added. | |
""" | |
return Concat( | |
*[ | |
Case( | |
When(f"{field}__isnull", Value("")), | |
default=Concat(Value(seperator), F(field)), | |
output_field=CharField(), | |
) | |
for field in fields], | |
output_field=CharField() | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment