0
votes

I've got the following serializer:

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',]

and the following test:

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)

When I print serializer.data on the screen, I'm getting:

[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)])]

after passing the queryset to the serializer and printing its data, isn't supposed to print in JSON format? what am I missing?

1

1 Answers

5
votes

There isn't any problem with your solution because serializer data always returns an ordered dict type of serialized data. Viewsets of rest_framework will handle it for you and reformat this object to json type (for example when you have return Response(serializer.data) it will change all input data format to json format). There are lots of ways if you want to see the json format of your data, for instance:

import json

data = json.dumps(serializer.data)

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

or you can use print(dict(serializer.data[0]) or any other index to change the format of it to dictionary type. But if you want to test your endpoints you should use rest API test cases and then assert your response in your test cases. For more information you can use rest framework docs about it's builtin test cases.