最近项目中前端向Django后端请求用户信息列表,其中涉及到两个ManyToMany的field拼接,想到了用GROUP_CONCAT实现。期初采用了extra的方案,但因为涉及到sql语句的直接编写,通用性不强,且感觉有点LOW……因此希望用Django 的ORM实现。参考了hj009zzh的下面这个帖子:
单个ManyToMany的field查询中没有任何问题,但是两个以上同时查询时,每一个field的输出都会出现重复拼接的现象,因此必须设
distinct=True
但此时会报错,提示GROUP_CONCAT不能设定DISTINCT,其原因在于定义GROUP_CONCAT时漏掉了一句:
class GroupConcat(Aggregate):
function = 'GROUP_CONCAT'
template = '%(function)s(%(distinct)s%(expressions)s%(ordering)s%(separator)s)'
allow_distinct = True
def __init__(self, expression, distinct=False, ordering=None, separator=',', **extra):
super(GroupConcat, self).__init__(
expression,
distinct='DISTINCT ' if distinct else '',
ordering=' ORDER BY %s' % ordering if ordering is not None else '',
separator=' SEPARATOR "%s"' % separator,
output_field=CharField(),
**extra
)
即“allow_distinct = True”,设定此项后,完美完成了所需功能!