我有那么一天,我认为这个项目上的事情会很容易,但结果却并非如此.我觉得在我的挫败感中,我一定忽略了一些非常简单的东西.
我有一个API观,它传递一个UUID来标识游戏故事的"章节",判断当前登录的用户是否有条目表明他们完成了挑战,如果有,则返回下一个Hunt线索(与章节挑战不同)或0,供我在UI中处理.
由于某些原因,它不会在查询中返回任何结果.然而,当我输出原始的SQL查询(queryset.ery)时,该查询返回预期的结果.
任何帮助都不胜感激.
观
class GetHuntClue(API观):
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 = HuntClue串行器(queryset, context=serializer_context)
return Response(serializer.data)
else:
return HttpResponse(already_ans, content_type="text/plain")
串行器
class HuntClue串行器(serializers.模型串行器):
class Meta:
model = HuntClue
#fields = '__all__'
fields = ("id", "hunt_title", "hunt_clue", "hunt_chapter")
模型
class HuntClue(models.模型):
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 `HuntClue串行器`.
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