【发布时间】:2021-11-26 16:28:22
【问题描述】:
我正在构建的 Django 应用程序中有一项服务,我想在其中处理获取和发布请求。我虽然应该重用我构建的序列化程序,但在我发现的示例中,每当有人想要使用序列化程序时,他们都会创建一个新对象。
这是一种实现,其中多次调用序列化程序类以创建多个实例,每次请求到达时一个:
from django.http.response import JsonResponse
from django.http.request import RAISE_ERROR, HttpRequest
from rest_framework.parsers import JSONParser
from rest_framework import status
from models import Instrument
from serializers import InstrumentsSerializer
class InstrumentsService():
def __init__(self):
self.serializer: InstrumentsSerializer = None
def get_instruments_by_type(self, instrument_type: str):
if instrument_type is not None:
instruments = Instrument.objects.all()
instruments.filter(instrument_type__icontains=instrument_type)
instruments_serializer = InstrumentsSerializer(instruments, many=True)
else:
raise ValueError("Value type None is not acceptable for 'instrument_type'")
return instruments_serializer.data
def add_instrument(self, instrument_data: Instrument):
instrument_serializer = InstrumentsSerializer(data=instrument_data)
if instrument_serializer.is_valid():
instrument_serializer.save()
如何使用相同的序列化程序并每次向其传递不同的数据?因为在我提供的示例中,数据是在初始化期间传递的。
【问题讨论】:
-
你不能。序列化程序仅在初始化期间接受数据。您不能将新数据传递给 Serializer 对象。
-
该死的!好的,谢谢
-
为什么不使用 rest_framework 中的 serializers.ModelSerializer?
-
@EliasPrado 我正在使用它。 InstrumentSerializer 是我制作的序列化器,它继承自它
标签: python django django-rest-framework django-views