custom serializer list of custom objects in django
To serialize a list of custom objects in Django, you can use the Django's built-in serializer class serializers.ModelSerializer. Here is an example:
- Define your custom object model:
from django.db import models
class MyObject(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
# other fields
- Create a serializer for your custom object:
from rest_framework import serializers
from .models import MyObject
class MyObjectSerializer(serializers.ModelSerializer):
class Meta:
model = MyObject
fields = '__all__'
- Create a view that returns a list of your custom objects:
from rest_framework import generics
from .serializers import MyObjectSerializer
from .models import MyObject
class MyObjectList(generics.ListAPIView):
queryset = MyObject.objects.all()
serializer_class = MyObjectSerializer
- Add the URL of your view to your Django urls.py:
from django.urls import path
from .views import MyObjectList
urlpatterns = [
path('myobjects/', MyObjectList.as_view(), name='myobject-list'),
]
Now, when you go to the URL /myobjects/ in your browser or send a GET request to that URL, you will get a serialized list of your custom objects.
原文地址: https://www.cveoy.top/t/topic/1p7 著作权归作者所有。请勿转载和采集!