,例外价值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数,例外值:'很多'是此函数的无效关键字参数 views.py
from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from student.models import Student
from student.serializers import StudentSerializer
@api_view(['GET', 'POST'])
def Student_list(request):
if request.method == 'GET':
snippets = Student.objects.all()
serializer = Student(Student, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = Student(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'PUT', 'DELETE'])
def Student_detail(request, pk):
try:
snippet = Student.objects.get(pk=pk)
except Student.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = Student(snippet)
return Response(serializer.data)
elif request.method == 'PUT':
serializer = Student(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE':
snippet.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
models.py
from django.db import models
class Student(models.Model):
id=models.IntegerField(primary_key=True)
fname=models.CharField(max_length=20)
lname=models.CharField(max_length=20)
cnt=models.IntegerField()
class Meta:
ordering=('id',)
serializers.py
from rest_framework import serializers
from student.models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields=('id','fname','lname','cnt')
def create (self,validated_data):
return Student.objects.create(**validated_data)
def update(self,instance,validated_data):
instance.id=validated_data.get('id',instance.id)
instance.fname=validated_data.get('fname',instance.fname)
instance.lname=validated_data.get('lname',instance.lname)
instance.cnt=validated_data.get('cnt',instance.cnt)
instance.save()
return instance
答案 0 :(得分:0)
在Student_list
视图中,您需要将serializer = Student(Student, many=True)
替换为serializer = StudentSerializer(snippets, many=True)
:
if request.method == 'GET':
snippets = Student.objects.all()
serializer = StudentSerializer(snippets, many=True)
return Response(serializer.data)
Sudent
是模型类,但是对于序列化,您需要使用序列化程序类并将其传递给Student实例或学生查询集。