如何通过Django Rest Framework API只返回1条记录?(多条记录的问题=False)

2fjabf4q  于 2022-12-20  发布在  Go
关注(0)|答案(1)|浏览(94)

我有一个简单的Django Rest Framework API,我希望它只返回1条记录。但是,当我设置many=False时,它不再工作。我该如何解决这个问题?

API如下:(序列化器和模型如下)

class Expense_View_API(APIView):
    permission_classes = [IsAuthenticated, ]

    def get(self, request):

        param_xid = request.GET.get('id','')

        if param_xid != "":
            expenses_recordset = Expenses.objects.filter(xid=param_xid)
            serializer = Expenses_Serializer(expenses_recordset, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)

        else:
            return Response("BAD REQUEST: Missing 'id' Parameter", status=status.HTTP_400_BAD_REQUEST)

它返回:(很好,只是我不需要方括号)

[
    {
        "xid": 111,
        "xdate": "2021-02-15T00:00:00Z",
        "xseller": "Amazon",
        "xamount": "30.00",
    }
]

**问题:**当我设置serializer = Expenses_Serializer(expenses_recordset, many=False)时,它现在返回此空数据并删除我的xid字段。为什么?

{
    "xdate": null,
    "xseller": null,
    "xamount": null,
}

我希望它返回:

{
    "xid": 111
    "xdate": "2021-02-15T00:00:00Z",
    "xseller": "Amazon",
    "xamount": "30.00",
}

下面是我的序列化器和数据模型:

class Expenses_Serializer(serializers.ModelSerializer):

    class Meta:
        model = Expenses
        fields = ('xid', 'xdate', 'xseller', 'xamount')

class Expenses(models.Model):
    xid = models.AutoField(db_column='xID', primary_key=True)  # Field name made lowercase.
    xdate = models.DateTimeField(db_column='xDate', blank=True, null=True)  # Field name made lowercase.
    xseller = models.CharField(db_column='xSeller', max_length=50, blank=True, null=True)  # Field name made lowercase.
    xamount = models.DecimalField(db_column='xAmount', max_digits=19, decimal_places=2, blank=True, null=True)  # Field name made lowercase.

    # Metadata
    class Meta:
        managed = False
        db_table = 'Expenses'
        app_label  = 'Expenses'

    # Methods
    def get_absolute_url(self):
        """Returns the url to access a particular instance of MyModelName."""
        return reverse('model-detail-view', args=[str(self.id)])

    def __str__(self):
        """String for representing the MyModelName object (in Admin site etc.)."""
        return self.my_field_name

感谢您抽出宝贵时间!

xeufq47z

xeufq47z1#

问题在于,您使用过滤器API序列化整个QuerySet(列表),而实际上,您需要序列化单个对象示例:

class Expense_View_API(APIView):
    permission_classes = [IsAuthenticated, ]

    def get(self, request):

        param_xid = request.GET.get('id','')

        if param_xid != "":
            expense_recordset = Expenses.objects.get(xid=param_xid)
            serializer = Expenses_Serializer(expense_recordset)
            return Response(serializer.data, status=status.HTTP_200_OK)

        else:
            return Response("BAD REQUEST: Missing 'id' Parameter", status=status.HTTP_400_BAD_REQUEST)

此外,我建议使用get_object_or_404快捷方式来清理您的视图。

相关问题