简体   繁体   English

在 graphene-django 中创建自定义 object 以返回分组计数

[英]Create Custom object in graphene-django to return grouped counts

I'm trying to build a way to return grouped counts of another object based on specific filtering criteria.我正在尝试构建一种方法来根据特定的过滤条件返回另一个 object 的分组计数。 As an example, given the following model with the following sample data, I'd like to create a call that will return the following result:例如,给定以下 model 和以下示例数据,我想创建一个将返回以下结果的调用:

The Model: Model:

class Task(models.Model):
    class Meta:
        db_table = "task"

    id = models.UUIDField(
        db_column="task_id", primary_key=True, default=uuid.uuid4, editable=False
    )
    start_date = models.DateTimeField()
    due_date = models.DateTimeField()
    task_status = models.CharField(max_length=250)
    )

Sample Data:样本数据:

id           start_date     due_date     task_status
624d8126...  2021-01-01     2021-03-02   in progress

171a7969...  2021-03-01     2021-02-28   assigned

92f6e493...  2021-04-01     2021-04-10   completed

a5722f6f...  2021-04-03     2021-04-08   assigned

e884efcb...  2021-05-01     2021-04-30   available

Desired Result (or something similar)期望的结果(或类似的东西)

getTaskCounts
{
    taskCount
    {
      countType: "behind schedule",
      count: 2
    },
    taskCount
    {
      countType: "in progress",
      count:  2
    },
    taskCount
    {
      countType: "completed",
      count:  1
    }

}

Note I'm grouping the various statuses based on the desired result.注意我根据期望的结果对各种状态进行了分组。

You can define custom object type like:您可以定义自定义 object 类型,例如:

class TaskCount(graphene.ObjectType):
    count_type = graphene.String()
    count = graphene.Int()

and then define another object to return a grouped list of them like:然后定义另一个 object 以返回它们的分组列表,例如:

from django.db.models import Count

class TaskCounts(graphene.ObjectType):
    task_counts = graphene.List(TaskCount)

    def resolve_task_counts(self, info):
        # Query for grouping -- test in Django shell
        grouped_tasks = Task.objects
            .values('task_status')
            .annotate(count=Count('task_status'))
            .order_by()
        return [
            TaskCount(count_type=grouped_task.task_status, count=grouped_task.count) for grouped_task in grouped_tasks
         ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM