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:

  1. 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
  1. 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__'
  1. 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
  1. 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.

custom serializer list of custom objects in django

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

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