2
class Project(models.Model):
    name = models.CharField(max_length=189)

class Customer(models.Model):
    name = models.CharField(max_length=189)
    is_deleted = models.BooleanField(default=False)
    project = models.ForeignKey(Project, related_name="customers")

class Message(models.Model):
    message = models.TextField()
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="messages")
    created_at = models.DateTimeField(auto_now_add=True)

我正在使用以下查询集来获取某个项目下的所有客户,这些客户由最后发消息的人订购。

qs = Customer.objects.filter(messages__isnull=False) \
.annotate(last_message=Max('messages__created_at')).order_by('-last_message')

现在我想根据带注释的查询集使用基本的石墨烯查询(不是中继)来获取项目以及与该项目关联的客户。我可能还有第二个用例,我需要根据 Customer 表中的字段(例如,具有 is_deleted=False 的客户)过滤 project.customers.all() 查询集。

目前在我的graphql模式中,我有,

class ProjectNode(DjangoObjectType):
    class Meta:
        model = Project

class CustomerNode(DjangoObjectType):
    class Meta:
        model = Customer

class Query(graphene.ObjectType):
    project = graphene.Field(ProjectNode, id=graphene.Int(), token=graphene.String(), )
    top_chat_customers = graphene.Field(CustomerNode, project_id=graphene.Int())

     def resolve_project(self, info, **kwargs):
        pk = kwargs["id"]
        return Project.objects.filter(id=pk).first()

    def resolve_top_chat_customers(self, info, **kwargs):
        project = Project.objects.filter(id=kwargs["project_id"]).first()
        return Customer.objects.filter(project=project, messages__isnull=False) \
.annotate(last_message=Max('messages__created_at')).order_by('-last_message')

在这里,当我尝试通过提供项目 ID 单独获取客户列表时,它显示错误:“收到不兼容的实例...”

关于如何从项目节点中获取客户列表并作为单独的 top_chat_customers 查询的任何想法?

任何帮助表示赞赏。谢谢!

4

1 回答 1

3

该方法resolve_top_chat_customers返回一个可迭代的查询集,而不是一个单独的Customer对象,因此Query您需要指定要返回一个列表:

top_chat_customers = graphene.List(CustomerNode, project_id=graphene.Int())

此外,查询中的任何带注释的字段都不会自动成为架构的一部分。如果您想查看它们,则需要明确添加它们:

class CustomerNode(DjangoObjectType):
    last_message = graphene.String()

    class Meta:
        model = Customer

    def resolve_last_message(self, info):
        # Returns last message only if the object was annotated
        return getattr(self, 'last_message', None)
于 2018-07-19T14:31:44.977 回答