개발 이야기/Django
Django 에서 GROUP_CONCAT 커스텀 사용 시 order_by, separator 추가하기
_ppuing
2024. 2. 27. 16:33
반응형
class CustomConcat(Aggregate):
function = 'GROUP_CONCAT'
allow_distinct = True
def __init__(self, expression, distinct=False, **extra):
# order by = group_concat 의 정렬 기준
# separator = group_concat 의 구분자(default = ",")
expr_separator = ''
expr_order_by = ''
order_by = extra.get('order_by')
separator = extra.get('separator')
if order_by:
expr_order_by = f' ORDER BY {order_by} '
if separator:
expr_separator = f' SEPARATOR \'{separator}\' '
self.template = f"%(function)s(%(distinct)s%(expressions)s{expr_order_by}{expr_separator})"
super(CustomConcat, self).__init__(expression,
distinct='DISTINCT ' if distinct else '',
output_field=CharField(),
**extra)
실제 사용 시에는
data = Table.objects.filter(**condition).annotate(
concat_ids=CustomConcat('column1', separator='\\n', order_by='Table.id')
)
처럼 구현하며, concat_ids 가 엔터로 구분되어 리턴 된다. 또한 ordering을 원래 하지 않으면 간혹 id가 뒤죽박죽으로 정렬되는 문제가 있으므로 위 처럼 order_by 부분을 id를 넣어서 활용할 수 있다.
반응형