gpt4 book ai didi

django - 在 Django Rest Framework 中根据 ID 在 API 中检索数据

转载 作者:行者123 更新时间:2023-12-04 01:40:42 26 4
gpt4 key购买 nike

我做了一个django函数的APIView

Views.py

class TakenQuizListViewAPI(APIView):

def get(self, request, *args, **kwargs):
queryset = self.request.user.supplier.taken_quizzes.select_related('quiz', 'quiz__truck_type').order_by(
'quiz__posted_on')

query = suppliertakenquizSerializer(queryset, many=True).data

return Response(query)

它返回这样的数据:

    {
"id": 5,
"score": 0.0,
"date": "2019-08-20T13:31:15.156691",
"least_bid": 99,
"confirmed": "Not Confirmed",
"supplier": 32,
"quiz": 16
},

如何在 API 中获取测验的所有详细信息??

预期输出:

{
"id": 5,
"score": 0.0,
"date": "2019-08-20T13:31:15.156691",
"least_bid": 99,
"confirmed": "Not Confirmed",
"supplier": 32,
"quiz": { "foo": "",
"bar": ""
}
},

序列化器:

class suppliertakenquizSerializer(serializers.ModelSerializer):

class Meta:
model = TakenQuiz
fields = "__all__"

模型.py:

class TakenQuiz(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='taken_quizzes')
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='taken_quizzes')
score = models.FloatField()
date = models.DateTimeField(auto_now_add=True)
least_bid = models.IntegerField(default=0)
confirmed = models.CharField(max_length=100, default='Not Confirmed')

更新我尝试了什么:

我更新了序列化程序,当它获得测验 ID 时它应该返回测验数据,但我不确定这是否正确

class suppliertakenquizSerializer(serializers.ModelSerializer):
quiz = serializers.SerializerMethodField()

def get_items(self, obj):
try:
serializer = createrfqSerializer(Quiz.objects.get(pk=int(obj.)))
quiz_data = serializer.data
except ItemBatch.DoesNotExist:
pass
return quiz_data


class Meta:
model = TakenQuiz
fields = "__all__"

最佳答案

我们在序列化器元类中有 depth 参数。我们可以像下面这样使用它。 depth=1 将检索关系的所有字段。

class suppliertakenquizSerializer(serializers.ModelSerializer):

class Meta:
model = TakenQuiz
fields = "__all__"
depth = 1

引用:https://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization

关于django - 在 Django Rest Framework 中根据 ID 在 API 中检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57585517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com