serializer list of objects in django
In Django, you can use serializers to convert complex Python objects, such as querysets and model instances, into native Python datatypes that can be easily rendered into JSON, XML, or other content types. Here's how to create a serializer list of objects in Django:
- Define your model:
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
price = models.DecimalField(max_digits=5, decimal_places=2)
- Create a serializer class for your model:
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'title', 'author', 'price')
- In your view, create a queryset of the objects you want to serialize:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET'])
def book_list(request):
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
- Finally, add a URL pattern to your project's urls.py file that maps to your view:
from django.urls import path
from .views import book_list
urlpatterns = [
path('books/', book_list, name='book-list'),
]
Now, when you visit the /books/ URL in your browser, you should see a JSON response containing a list of serialized Book objects.
原文地址: https://www.cveoy.top/t/topic/1pV 著作权归作者所有。请勿转载和采集!