如何从 Django 模型正确获取数据到 Django REST 框架

How to get data correctly from a django model to Django REST framework

我正在使用 Python 3.9 和 Django 3.1.6。我在 models.py 中有一个很长的模型。简短的版本是这样的:

class Check (models.Model):
    @property
    def total_body_fat_percentage(self):
        if self.client_gender == "M":
            total_body_fat_percentage = (self.Yuhasz * 0.097) + 3.64
            pass
        else:
            total_body_fat_percentage = total_body_fat_percentage = float((self.Yuhasz * 0.1429) + 4.56)
        return total_body_fat_percentage

    @property
    def muscle_weight_percentage(self):
        muscle_weight_percentage =self.muscle_weight*100/self.weight
        return muscle_weight_percentage

这些字段 return 一个浮点数。类似于 14.407.

当然还有Yuhasz、client_gender等其他字段。 我需要将这些值放入 JSON。我尝试在 serializer.py 上使用以下序列化程序:

class PercentagesSerializer(ModelSerializer):

    class Meta:
        model = Check
        fields = ('total_body_fat_percentage', 'muscle_weight_percentage')

我在 views.py 上有以下 class:

class PercentagesAPI(APIView):

    authentication_classes = []
    permission_classes = []

    serializer = PercentagesSerializer
    
    def get(self, request, format=None):
        lista = Check.objects.all()
        print(lista)
        response = self.serializer(lista)
        print(response)
        json_response= json.dumps(response.data)
        print(json_response)
        data = {
            'percentages': json_response
        }
        
        return Response(response.data)

但是return没有数据。 Shell 控制台声明它获取了查询集,它获取了字段,但它似乎没有获取值:

<QuerySet [<Check: Check object (1)>]>
PercentagesSerializer(<QuerySet [<Check: Check object (1)>]>):
    total_body_fat_percentage = ReadOnlyField()
    muscle_weight_percentage = ReadOnlyField()
{}

提前感谢您的建议和帮助!

您填充 data 变量但从未使用它。相反,你 return response.data

 response = self.serializer(lista)
 data = {
            'percentages': json_response
        }
        
 return Response(response.data)

我认为这是解决方案:

 response = self.serializer(lista, many=True) # <-- many
 data = {
            'percentages': json_response
        }
        
 return Response(data) # <-- data

查询做了 return 事情 - 打印显示 1 record/object: Check object (1)