Django得到了很多独特的东西

时间:2018-01-09 22:14:39

标签: python django django-models

class Word(Model):
    word = CharField()
    categories = ManyToManyField('Category')

class Category(Model):
   name = CharField()

获取所有唯一类别列表的最佳方法是什么?

例如,如果我有

apple -> General, Garden
pear -> General, Garden
computer -> IT

我想获得以下列表列表

(General, Garden)
(IT, )

我需要PostgreSQL解决方案。

1 个答案:

答案 0 :(得分:1)

假设你有GroupConcat这样的功能:

class GroupConcat(models.Aggregate):
    function = 'GROUP_CONCAT'
    template = '%(function)s(%(distinct)s%(expressions)s%(ordering)s%(separator)s)'

    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=models.CharField(),
            **extra
        )

然后你可以这样做:

Word.objects.all().annotate(
        category_names=GroupConcat('categories__name')
    ).values_list('category_names').distinct()

PS。这是一个MySQL解决方案。

相关问题