You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取所有Cat的最新CatRecords?Django GraphQL查询报错求助

问题分析

你遇到的报错核心原因有两个:

  1. 字段类型不匹配:latest_record被定义为单个CatRecordType,但你的resolve方法返回的是包含多条记录的QuerySet字典列表,Graphene无法将集合映射为单个对象。
  2. 返回数据格式错误:使用.values()返回的是字典结构,而非Django模型实例,Graphene无法将其解析为对应的ObjectType。

解决方案

要实现「所有猫咪+对应最新记录+按记录时间排序」的需求,我们需要调整Type定义和查询逻辑:

1. 修改CatType,新增最新记录字段

让猫咪对象可以携带自身的最新记录:

class CatRecordType(graphene.DjangoObjectType):
    class Meta:
        model = CatRecords
        fields = ("id", "cat_id", "status", "created_time")

class CatType(graphene.DjangoObjectType):
    # 新增字段,关联单条最新记录
    latest_record = graphene.Field(CatRecordType)

    class Meta:
        model = Cat
        fields = ("id", "name")

2. 调整Query类,新增专用查询字段

替换原有的latest_record字段,新增cats_with_latest_record来返回带最新记录的猫咪列表:

from django.db.models import OuterRef, Subquery, Prefetch

class Query(graphene.ObjectType):
    all_cats = graphene.List(CatType)
    cat = graphene.Field(CatType, cat_id=graphene.UUID())
    # 新增字段:返回带最新记录的猫咪列表
    cats_with_latest_record = graphene.List(CatType)

    def resolve_all_cats(self, info, **kwargs):
        return Cat.objects.all()

    def resolve_cat(self, info, cat_id):
        # 注意:Cat模型主键是id,所以用id=cat_id匹配
        return Cat.objects.get(id=cat_id)

    def resolve_cats_with_latest_record(self, info):
        # 子查询:获取每只猫的最新记录ID
        latest_record_subquery = CatRecords.objects.filter(
            cat_id=OuterRef("id")
        ).order_by("-created_time").values("id")[:1]
        
        # 给Cat标注最新记录ID,再通过预取关联获取完整记录
        cats = Cat.objects.annotate(
            latest_record_id=Subquery(latest_record_subquery)
        ).prefetch_related(
            Prefetch(
                "catrecords_set",  # Cat到CatRecords的反向关联名(默认是模型名小写+_set)
                queryset=CatRecords.objects.filter(id=OuterRef("latest_record_id")),
                to_attr="latest_record"
            )
        ).order_by("-catrecords__created_time")  # 按最新记录的创建时间倒序排序
        
        return cats

3. 正确的GraphQL查询语句

query {
  catsWithLatestRecord {
    id
    name
    latestRecord {
      id
      status
      createdTime
    }
  }
}

关键说明

  • 反向关联名catrecords_set:如果你的CatRecords模型中给外键cat_id设置了related_name,请替换为对应的名称。
  • 排序逻辑:order_by("-catrecords__created_time")确保结果按每只猫最新记录的创建时间倒序排列。

内容的提问来源于stack exchange,提问作者bao.le

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 12:05:06