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

APIView查询无结果且序列化报错问题求助

问题解决思路

核心错误原因

你遇到的AttributeError是因为序列化器默认处理单个模型实例,但你传入的是QuerySet(查询集合),序列化器会尝试从QuerySet对象上直接获取hunt_title字段,而QuerySet本身没有这个属性,自然报错。

修复步骤

1. 修正序列化器调用

在实例化HuntClueSerializer时,添加many=True参数,告诉序列化器要处理多个对象:

serializer = HuntClueSerializer(queryset, context=serializer_context, many=True)

如果每个章节只会对应一条HuntClue记录,也可以用.first()获取单个实例,这样就不需要many=True:

queryset = HuntClue.objects.filter(hunt_chapter=chapter_uuid).first()
serializer = HuntClueSerializer(queryset, context=serializer_context)

2. 优化查询逻辑(可选但推荐)

  • 查询GameActivityType时用get代替filter+first:如果"Correct Challenge Answer"是固定类型,用get更严谨,不存在时会抛出明确异常:
    log_type = GameActivityType.objects.get(activity_type_name="Correct Challenge Answer")
    
  • 用exists()替代count()判断是否存在记录:exists()只检查是否有匹配记录,比count()更高效:
    already_ans = GameActivity.objects.filter(
        user=curr_user,
        activity_chapter=chapter_uuid,
        activity_type=log_type
    ).exists()
    
  • 修复HuntClue的过滤条件:hunt_chapter是ForeignKey关联的Chapter模型,直接传UUID字符串可能存在类型不匹配,建议先获取Chapter实例再过滤:
    try:
        chapter = Chapter.objects.get(uuid=chapter_uuid)
    except Chapter.DoesNotExist:
        return Response({"error": "Chapter not found"}, status=status.HTTP_404_NOT_FOUND)
    queryset = HuntClue.objects.filter(hunt_chapter=chapter)
    

完整修正后的视图代码示例

from rest_framework import status

class GetHuntClue(APIView):

    def get(self, request, **kwargs):
        serializer_context = {'request': request}
        chapter_uuid = self.kwargs['chapter_uuid']
        curr_user = self.request.user

        # 获取正确挑战答案的日志类型
        try:
            log_type = GameActivityType.objects.get(activity_type_name="Correct Challenge Answer")
        except GameActivityType.DoesNotExist:
            return Response({"error": "Activity type not found"}, status=status.HTTP_404_NOT_FOUND)

        # 检查用户是否完成该章节挑战
        already_ans = GameActivity.objects.filter(
            user=curr_user,
            activity_chapter=chapter_uuid,
            activity_type=log_type
        ).exists()

        if already_ans:
            # 获取对应章节的HuntClue
            try:
                chapter = Chapter.objects.get(uuid=chapter_uuid)
                hunt_clue = HuntClue.objects.filter(hunt_chapter=chapter).first()
                if not hunt_clue:
                    return Response({"error": "No hunt clue found for this chapter"}, status=status.HTTP_404_NOT_FOUND)
                serializer = HuntClueSerializer(hunt_clue, context=serializer_context)
                return Response(serializer.data)
            except Chapter.DoesNotExist:
                return Response({"error": "Chapter not found"}, status=status.HTTP_404_NOT_FOUND)
        else:
            return HttpResponse("0", content_type="text/plain")

内容的提问来源于stack exchange,提问作者Bring Coffee Bring Beer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 07:33:23