根据Django Rest Framework中的ID检索API中的数据

时间:2019-08-21 06:20:01

标签: django django-rest-framework

我制作了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__"

Model.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__"

4 个答案:

答案 0 :(得分:2)

您可以尝试下面的序列化程序类吗?您必须为测验数据创建一个Serializer类,并在Serializermethod字段中使用相同的类。

尝试一下。

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

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

答案 1 :(得分:0)

我认为您不需要放到SerializerMethodField。当您尝试执行的操作无法以任何其他方式执行时,将使用该类型的字段。当我在代码上看到它时,通常是个坏习惯。

我认为您1在“嵌套关系”部分中对您的需求进行了说明。基本上,在字段声明中,您指向另一个将对该字段进行序列化的序列化程序。这使您可以以声明的方式定义所需的内容。如您所见,还有许多其他类型的字段可以执行许多操作。 DRF文档太神奇了!

答案 2 :(得分:0)

我在序列化程序中创建了一个函数来实现它。

class suppliertakenquizSerializer(serializers.ModelSerializer):

    quiz = serializers.SerializerMethodField()

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


    class Meta:
        model = TakenQuiz
        fields = "__all__"

答案 3 :(得分:0)

我们在序列化器元类中具有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