无法从包含许多对象的列表中获取数据

时间:2017-10-23 10:50:52

标签: python django request django-rest-framework

我正在尝试request.data.get(' student_name')但它说该列表没有属性get。我只想在传递给序列化器之前得到所有学生的名字。我正在以

的形式发送POST请求数据
[
{"student_name": "jack", "last_name": "cale", "fathers_name":"carlos"},
{"student_name": "alex", "last_name": "magasa", "fathers_name":"greg"},
{"student_name": "sia", "last_name": "gunns", "fathers_name":"brett"},
{"student_name": "jacob", "last_name": "woods", "fathers_name":"john"}
] 

my views.py

@api_view(['POST'])
def add_students(request):
student_name = request.data.get('student_name')
fathers_name = request.data.get('fathers_name')
serializer = StudentsSerializer(data=request.data, many=True)
if serializer.is_valid():
    serializer.save()
    return Response("success")
else:
    return Response(serializer.errors)

我的serializers.py

class StudentsSerializer(serializers.ModelSerializer):

class Meta:
    model = Students
    fields = ('student_name', 'last_name', 'fathers_name')

my models.py

class Students(models.Model):
student_name = models.CharField(max_length=100, null=True)
last_name = models.CharField(max_length=100, null=True)
fathers_name = models.CharField(max_length=100, null=True)

2 个答案:

答案 0 :(得分:1)

您正试图从列表中获取值,因此您必须遍历列表

for data in request.data:
    student_name = data.get('student_name')
    father_name = data.get('father_name')

答案 1 :(得分:1)

这似乎是关于请求对象格式的问题。我的两分钱是值得在方法开头使用import ipdb; ipdb.set_trace(),然后使用printdir来了解对象的外观。由于Django有很多特定于django的对象,这在很多情况下都有帮助。