gpt4 book ai didi

python - 不显示使用 SerializerMethodField 添加的字段

转载 作者:太空宇宙 更新时间:2023-11-03 21:16:17 24 4
gpt4 key购买 nike

这些是我的模型.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()

我想做的是制作一个序列化器,它使用网址“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
}
]
}

最佳答案

我认为您在编写代码时并没有理解什么是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 时,它将处理所有 getpatchputdelete 方法。您不需要在 View 中覆盖它们。因此以下代码足以满足您的需求。

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

关于python - 不显示使用 SerializerMethodField 添加的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54682704/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com