Skip to content

Instantly share code, notes, and snippets.

@stuaxo
Created April 5, 2022 12:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuaxo/ed770677426ab807cbbb4b452ad2c689 to your computer and use it in GitHub Desktop.
Save stuaxo/ed770677426ab807cbbb4b452ad2c689 to your computer and use it in GitHub Desktop.
Django concatenate non null fields. #snippet
# 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