这些是我的模特。py
class Grade(models.Model):
grade = models.CharField(max_length=255, primary_key=True)
class Student(models.Model):
name = models.CharField(max_length=255)
grade = models.ForeignKey(grade, on_delete=models.CASCADE)
rollno = models.BigIntegerField()
我想做的是制作一个序列化程序,该序列化程序使用url:“ check / {str:pk} /”为我提供所有学生到特定年级的列表(实现获取和删除方法)。 在我的序列化器中,我试图将两个模型结合起来,如下所示:
class MySerializer(serializers.ModelSerializer):
allStudents = serializers.SerializerMethodField()
class Meta:
model = Grade
fields = ("grade", "allStudents")
def get_allStudents(self, obj):
s_list = []
fields = ['name', 'grade', 'rollno']
for stds in obj:
s_list.append(model_to_dict(stds, fields=fields))
return s_list
我的views.py如下所示:
class IndividualGrade(generics.RetrieveUpdateDestroyAPIView):
'''
PUT check/{grade}/
GET check/{grade}/
DELETE check/{grade}/
'''
queryset = Grade.objects.all()
serializer_class = MySerializer
def get(self, request, *args, **kwargs):
try:
s1 = Grade.objects.get(grade=kwargs["pk"])
all_stds = Student.objects.filter(grade=s1)
a_grade = Grade.objects.get(grade=s1)
return Response(MySerializer(a_grade, all_stds ).data)
except Grade.DoesNotExist:
return Response(
data={
"message": "Grade with id: {} does not exist".format(kwargs["pk"])
},
status=status.HTTP_404_NOT_FOUND
)
def delete(self, request, *args, **kwargs):
try:
Grade.objects.get(grade=kwargs["pk"]).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
except Grade.DoesNotExist:
return Response(
data={
"message": "Grade with id: {} does not exist".format(kwargs["pk"])
},
status=status.HTTP_404_NOT_FOUND
)
这给了我以下错误:
"message": "Grade with id: grade9 does not exist"
虽然条目肯定存在。因为我可以删除它,所以它不会显示添加的字段。
对于不是马上就可以使用的序列化器,我真的很天真。
仍然不确定我在做什么错。 另外,我想知道是否可以在SerializerMethodFiled中使用另一个序列化器
编辑
1.更新
输入请求:http://127.0.0.1:8000/check/grade5/
JSON输入:
{
"grade": "grade5",
"allstudents": [
{
"name": "Shub",
"grade": "grade5",
"rollno": 4
}
]
}
答案 0 :(得分:0)
在您理解SerializerMethodField
是什么的同时,我认为您不是在这里编码。您不需要传递任何额外的内容即可使用SerializerMethodField
获取值。意味着,您不需要将all_stds
作为MySerializer
的参数来传递。因此,您应该像这样更新序列化器:
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ('name', 'grade', 'rollno')
class MySerializer(serializers.ModelSerializer):
def get_allStudents(self, obj):
# here obj is a Grade Object
# we can get all the students by `obj.student_set.all()` via reverse relationship
return StudentSerializer(obj.student_set.all(), many=True).data
此外,当您使用RetriveUpdateDestroyApiView时,它将处理所有get
,patch
,put
,delete
方法。您无需在视图中覆盖它们。因此,遵循以下代码即可满足您的需求。
class IndividualGrade(generics.RetrieveUpdateDestroyAPIView):
'''
PUT check/{grade}/
GET check/{grade}/
DELETE check/{grade}/
'''
queryset = Grade.objects.all()
serializer_class = MySerializer
# No more code is needed