[英]Create Custom object in graphene-django to return grouped counts
我正在嘗試構建一種方法來根據特定的過濾條件返回另一個 object 的分組計數。 例如,給定以下 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)
)
樣本數據:
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
}
}
注意我根據期望的結果對各種狀態進行了分組。
您可以定義自定義 object 類型,例如:
class TaskCount(graphene.ObjectType):
count_type = graphene.String()
count = graphene.Int()
然后定義另一個 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.