CodexBloom - Programming Q&A Platform

Django ORM raises 'Object of type Decimal is not JSON serializable' when serializing queryset

👀 Views: 79 💬 Answers: 1 📅 Created: 2025-07-16
django json decimal rest-framework Python

This might be a silly question, but I'm working with a frustrating scenario while trying to serialize a Django queryset containing Decimal fields into JSON. When I attempt to return a response from my Django REST framework view, I get the behavior: `Object of type Decimal is not JSON serializable`. I've tried using the built-in serializers provided by Django REST framework, but the behavior continues. Here's the relevant part of my model: ```python from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) ``` And this is how I’m trying to serialize the queryset in my view: ```python from rest_framework import generics from .models import Product from .serializers import ProductSerializer class ProductListView(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer ``` My serializer looks like this: ```python from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' ``` I've also tried manually converting the Decimal fields to strings in the serializer using a custom field, but that hasn’t resolved the scenario. For example: ```python class ProductSerializer(serializers.ModelSerializer): price = serializers.DecimalField(max_digits=10, decimal_places=2, coerce_to_string=True) ``` Despite these attempts, the behavior still occurs. I've ensured that my Django version is 4.1.7 and that all my dependencies are up to date. How can I resolve this scenario to successfully serialize my queryset without running into the JSON serialization behavior? My development environment is Windows. Am I missing something obvious? My development environment is Linux. Am I missing something obvious? Am I missing something obvious?