在 graphene-django 中创建自定义对象以 return 分组计数
Create Custom object in graphene-django to return grouped counts
我正在尝试构建一种方法,根据特定过滤条件 return 对另一个对象进行分组计数。例如,给定具有以下示例数据的以下模型,我想创建一个将 return 以下结果的调用:
模特:
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
}
}
请注意,我正在根据所需结果对各种状态进行分组。
您可以定义自定义对象类型,例如:
class TaskCount(graphene.ObjectType):
count_type = graphene.String()
count = graphene.Int()
然后将另一个对象定义为 return 它们的分组列表,例如:
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
]
我正在尝试构建一种方法,根据特定过滤条件 return 对另一个对象进行分组计数。例如,给定具有以下示例数据的以下模型,我想创建一个将 return 以下结果的调用:
模特:
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
}
}
请注意,我正在根据所需结果对各种状态进行分组。
您可以定义自定义对象类型,例如:
class TaskCount(graphene.ObjectType):
count_type = graphene.String()
count = graphene.Int()
然后将另一个对象定义为 return 它们的分组列表,例如:
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
]