Django Serializer Example: Convert Model to JSON
Sure, here's an example of how to use Django's serializer to convert a model object into JSON format:
- First, create a Django model with some fields:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=200)
pub_date = models.DateField()
price = models.DecimalField(max_digits=6, decimal_places=2)
- Next, create a serializer class for the
Bookmodel. This class will define how the model should be serialized into JSON format:
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['title', 'author', 'pub_date', 'price']
- In your Django view, instantiate an instance of the serializer class and pass in the object you want to serialize:
from django.http import JsonResponse
from .models import Book
from .serializers import BookSerializer
def book_detail(request, book_id):
book = Book.objects.get(pk=book_id)
serializer = BookSerializer(book)
return JsonResponse(serializer.data)
This will return a JSON response like this:
{
'title': 'The Great Gatsby',
'author': 'F. Scott Fitzgerald',
'pub_date': '1925-04-10',
'price': '15.99'
}
原文地址: https://www.cveoy.top/t/topic/ohtS 著作权归作者所有。请勿转载和采集!