Sure, here's an example of how to use Django's serializer to convert a model object into JSON format:

  1. 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)
  1. Next, create a serializer class for the Book model. 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']
  1. 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'
}
Django Serializer Example: Convert Model to JSON

原文地址: https://www.cveoy.top/t/topic/ohtS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录