【问题标题】:Create Custom object in graphene-django to return grouped counts在 graphene-django 中创建自定义对象以返回分组计数
【发布时间】:2021-11-26 00:51:01
【问题描述】:

我正在尝试构建一种方法来根据特定的过滤条件返回另一个对象的分组计数。例如,给定具有以下示例数据的以下模型,我想创建一个返回以下结果的调用:

模型:

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)
    )

样本数据:

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

期望的结果(或类似的东西)

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

}

请注意,我正在根据所需的结果对各种状态进行分组。

【问题讨论】:

    标签: django graphene-python graphene-django


    【解决方案1】:

    您可以定义自定义对象类型,例如:

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

    然后定义另一个对象以返回它们的分组列表,例如:

    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
             ]
    

    【讨论】:

    • 太棒了-谢谢。我没有意识到 ObjectTypes 可以这样嵌套。
    猜你喜欢
    • 2019-04-26
    • 2018-01-25
    • 2020-08-13
    • 2015-05-15
    • 2014-06-20
    • 1970-01-01
    • 2018-05-17
    • 2011-11-19
    • 2023-03-15
    相关资源
    最近更新 更多