Django Rest Framework 序列化程序正在打印元组而不是 json

Django Rest Framework serializer is printing tuples instead of json

我有以下序列化程序:

from rest_framework import serializers

from .models import Product

class ProductSerializer(serializers.ModelSerializer):
    """ Serializer for Product object """

    class Meta:
        model = Product
        fields = ['name', 'slug', 'description', 'image', 'price', 'active',]

和以下测试:

from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status

from .factories import ProductFactory
from .models import Product
from .serializer import ProductSerializer

PRODUCTS_URL = reverse('product-list')

def create_product(**params):
    """ Helper function to create a new product """
    return Product.objects.create(**params)

class PublicProductApiTests(TestCase):
    """
    Test the public products' API
    """

    def setUp(self):
        self.client = APIClient()

    
    def test_only_active_products_are_returned(self):

        ProductFactory.create_batch(2)
        
        products = Product.objects.all()
        serializer = ProductSerializer(products, many=True)

        print(serializer.data)

当我在屏幕上打印 serializer.data 时,我得到:

[OrderedDict([('name', 'Shane Fields'), ('slug', 'shane-fields'), ('description', 'Chance yourself conference.'), ('image', '/media/position/school.tiff'), ('price', '2.66'), ('active', False)]), OrderedDict([('name', 'Michael Hall'), ('slug', 'michael-hall'), ('description', 'Office city material room character number cause way.'), ('image', '/media/American/know.txt'), ('price', '-90244357.41'), ('active', True)])]

将查询集传递给序列化程序并打印其数据后,不应该以 JSON 格式打印吗?我错过了什么?

您的解决方案没有任何问题,因为序列化程序数据总是 returns 有序的字典类型的序列化数据。 rest_framework 的视图集将为您处理并将此对象重新格式化为 json 类型(例如,当您有 return Response(serializer.data) 时,它将所有输入数据格式更改为 json 格式)。如果您想查看数据的 json 格式,有很多方法,例如:

import json

data = json.dumps(serializer.data)

print(data)  # which will print json format of your data

或者您可以使用print(dict(serializer.data[0])或任何其他索引将其格式更改为字典类型。但是如果你想测试你的端点,你应该使用 rest API 测试用例,然后在你的测试用例中断言你的响应。有关更多信息,您可以使用 rest framework docs 关于它的内置测试用例。