django queryset用于统计字段中子字符串的出现次数

t1rydlwq  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(101)

我有一个名为Animal的模型,其中包含一个名为text的字段,该字段以动物名称开头,后跟可选文本,例如,cat - grey long hair

class Animal:
        text = models.TextField()

字符串
动物的一些例子包括:

animal1 = Animal()
animal1.text = "cat - grey long hair cat."
animal1.save()
animal2 = Animal()
animal2.text = "dog - black short hair dog."
animal2.save()
animal3 = Animal()
animal3.text = "non descriptive animal"
animal3.save()


我想计算以catdogfish开头的text的出现次数,并返回每个动物类别的计数。我假设如下:

queryset = models.Animal.objects.all()
    animal_summary = (
        queryset
        .annotate(
                cats=Count(
                    Case(
                        When(text__startswith="cats", then=1),
                        default=0,
                        output_field=IntegerField(),
                    )
                )
            )
        .annotate(
                dogs=Count(
                    Case(
                        When(text__startswith="dogs", then=1),
                        default=0,
                        output_field=IntegerField(),
                    )
                )
            )
        .annotate(
                fish=Count(
                    Case(
                        When(text__startswith="fish", then=1),
                        default=0,
                        output_field=IntegerField(),
                    )
                )
            )
        .values('cats', 'dogs', 'fish')
    )

    return {"animal_count": animal_summary}


但它似乎会计算条目的数量,而不考虑子字符串。

4uqofj5v

4uqofj5v1#

我可以用aggregation提供一个选项。我把这些行写进我的模型中,并计算出匹配的行。

from django.db.models import Count, Q

    queryset = models.Animal.objects.all()

    animal_summary = queryset.aggregate(
        cat=Count('pk', filter=Q(text__startswith='cat')),
        dog=Count('pk', filter=Q(text__startswith='dog')),
        non=Count('pk', filter=Q(text__startswith='non')),
    )

字符串
输入:

<QuerySet [<books: cat - grey long hair cat.>, <books: dog - black short hair dog.>, <books: non descriptive animal>, <books: cat>, <books: cat 33>]>


输出量:

{'cat': 3, 'dog': 1, 'non': 1}

相关问题