使用 ManyToMany 字段在 graphene-django 中发布连接数据

Issue joining data in graphene-django with a ManyToMany field

我一直在尝试为 return 在 ManyToMany 字段中使用连接数据查询集寻找一个很好的示例,但我没有找到一个。

给定以下模型:

class Task(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    task_assignee = models.ForeignKey("User")
    is_draft = models.Boolean(default=True)
    detail = models.ManyToManyField("Detail", through="TaskDetails")


class Detail(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    detail_name = models.CharField(max_length=250)

class TaskDetails(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    task = models.ForeignKey("Task", related_name="detail_tasks")
    detail = models.ForeignKey("Detail", related_name="task_details")
    detail_value = models.CharField(max_length=250)

我想要 return 任务的数据及其相关详细信息。根据 this question 上的回答,我将架构调整为以下内容:

class TaskDetailsType(DjangoObjectType):

    class Meta:
        model = TaskDetails
        fields = ("id", "detail_name", "detail_value")

        detail_name = graphene.String()

    def resolve_detail_name(value_obj, info):
        return value_obj.detail.detail_name


class TaskType(DjangoObjectType):

    class Meta:
        model = Task
        fields = ("id", "task_details")

    task_details = graphene.List(TaskDetailsType)

    def resolve_task_details(value_obj, info):
        return value_obj.detail_tasks

我运行宁的查询:

Task.objects.filter(task_assignee_id=info.context.user.id) \
    .filter(is_draft=False)

当我 运行 这样做时,我得到一个错误:

{'errors': [{'message': 'User Error: expected iterable, but did not find one for field TaskType.taskDetails.'}, {'message': 'User Error: expected iterable, but did not find one for field TaskType.taskDetails.'}, {'message': 'User Error: expected iterable, but did not find one for field TaskType.taskDetails.'}], 'data': {'getInboxTasks': [{'id': 'a430e49d-c9c3-4839-8f2c-aaebbfe9ef3a', 'taskDetails': None}, {'id': '74c8dacc-1bfd-437a-ae34-7e111075ac5e', 'taskDetails': None}, {'id': '10956caa-d74f-4a01-a5cf-9cac6a15c5a3', 'taskDetails': None}]}}

正如@schillingt 和石墨烯所暗示的那样,问题是 RelatedManager 不可迭代:

def resolve_task_details(value_obj, info):
    return value_obj.detail_tasks  # related manager

所以改变很简单:

def resolve_task_details(value_obj, info):
    return value_obj.detail_tasks.all()  # queryset -> iterable