APIView 查询未返回任何结果

问题描述 投票:0回答:1

有一天,我认为这个项目中的事情会很容易,但结果却并非如此。我觉得我一定在沮丧中忽略了一些非常简单的事情......

我有一个 APIView,它传入 UUID 来识别游戏故事的“章节”,检查当前登录的用户是否有一个条目表明他们完成了挑战,如果有,则返回下一个 Hunt Clue(不同的)来自章节挑战)或我在 UI 中处理的零。

由于某种原因,它没有在查询中返回任何结果。但是,当我输出原始 sql 查询 (queryset.query) 时,查询会返回预期的结果。

非常感谢任何帮助。

查看

class GetHuntClue(APIView):

    def get(self, request, **kwargs):
        serializer_context = {
            'request': request,
        }
        chapter_uuid = self.kwargs['chapter_uuid']
        curr_user = self.request.user
        #check to make sure it's answered then provide the appropriate hunt clue.  
        log_type = GameActivityType.objects.filter(activity_type_name="Correct Challenge Answer").first()
        already_ans = GameActivity.objects.filter(user=curr_user).filter(activity_chapter=chapter_uuid).filter(activity_type=log_type).count()
        if (already_ans):
            queryset = HuntClue.objects.filter(hunt_chapter=chapter_uuid)
            print(queryset.query)
            serializer = HuntClueSerializer(queryset, context=serializer_context)
            return Response(serializer.data)            
        else:
            return HttpResponse(already_ans, content_type="text/plain")

序列化器

class HuntClueSerializer(serializers.ModelSerializer):

    class Meta:
        model = HuntClue
        #fields = '__all__'
        fields = ("id", "hunt_title", "hunt_clue", "hunt_chapter")

型号

class HuntClue(models.Model):
    hunt_title = models.CharField(max_length=100)
    hunt_clue = models.CharField(max_length=500)
    hunt_chapter = models.ForeignKey(Chapter, on_delete=models.CASCADE, null=True, blank=True, related_name="chapter_hunt_clue")

    def __str__(self):
        return '%s' % (self.hunt_title)

原始查询:

SELECT "simgame_huntclue"."id", "simgame_huntclue"."hunt_title", "simgame_huntclue"."hunt_clue", "simgame_huntclue"."hunt_chapter_id" FROM "simgame_huntclue" WHERE "simgame_huntclue"."hunt_chapter_id" = f7ff3135-9212-47b1-a4f3-0d920c01c020

id |    hunt_title     |                 hunt_clue                  |           hunt_chapter_id            
----+-------------------+--------------------------------------------+--------------------------------------
  1 | Getting warmer... | Find the QR Code at the front of the room. | f7ff3135-9212-47b1-a4f3-0d920c01c020
(1 row)

但在视图中我收到错误:

AttributeError at /api/v1/gethuntclue/f7ff3135-9212-47b1-a4f3-0d920c01c020

Got AttributeError when attempting to get a value for field `hunt_title` on serializer `HuntClueSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'hunt_title'.

对此感到非常困惑......

感谢您的任何见解。

BCBB

django django-rest-framework django-views django-orm
1个回答
0
投票

您应该添加

many=True
。因为你设置的是
queryset
而不是
object

serializer = HuntClueSerializer(queryset, context=serializer_context, many=True)
© www.soinside.com 2019 - 2024. All rights reserved.