in my Django project, I have the following for serializers and views
serializers:
class AnimalSerializer(serializers.ModelSerializer):
class Meta:
model = Animal
fields = [
'pk',
'name',
'animal_type',
'weight',
'color',
]
views:
class AnimalRudView(generics.RetrieveUpdateDestroyAPIView):
serializer = AnimalSerializer
def create(self,request):
body = json.loads(request.body.decode('utf-8')
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM animals WHERE " + body['search'])
animal = [dict(zip([column[0] for column in cursor.description], row)) for row in cursor.fetchall()]
return Response(serializer.data)
In views, I get a request body with certain conditions ( as " search ": " weight>20 "), which gives me then all objects which match these conditions. I want to add this body to the serializer as well because I want to fill the fields list automatically. Do you have any idea how I can parse the body into the serializer?
Best regards
As an example from one of my custom post
methods from a class extending CreateAPIView
:
class BaseQuestionCheckerView(CreateAPIView):
serializer_class = MySerializer
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
# I can now access the validated data from my
# serialiser. But first I have to call is_valid():
try:
serializer.is_valid(raise_exception=True)
except Http404:
raise Http404
validated_data = serializer.validated_data
# common thing to do with serializer.validated_data
# is to return it.
return Response(serializer.validated_data, status=status.HTTP_200_OK)
Hope that gets you on the right track!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.