当我尝试创建一个Employee的新实例时,我收到一个错误:
django.utils.datastructures.MultiValueDictKeyError: "'bio'"
当我在' EmployeeAddView`类
中的post方法中print
这一行print(request.data)
时
我明白了:
<QueryDict: {'joining_date': ['2018-03-04'], 'designation': ['1'], 'csrfmiddlewaretoken': ['5AeZ7lFOE2Z5j8cPNNZtygh208Esw65tvf5fzka56nCAj1oUFWCR3fcNHuOok2JK'], 'bio.marital_status': ['1'], 'bio.preferred_language': ['English'], 'tax_id_number': ['333333333ed'], 'bio.birthday': ['2018-03-04'], 'bio.user.first_name': ['Jack'], 'department': ['2'], 'bio.user.last_name': ['Sparrow'], 'bio.phone_number': ['9999999'], 'bio.main_id_type_no': ['459opppp'], 'bio.id_type': ['1'], 'bio.gender': ['1'], 'account_number': ['qwwwwwwww3r3']}>
Internal Server Error: /hr/employee_add/
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/django/utils/datastructures.py", line 83, in __getitem__
list_ = super(MultiValueDict, self).__getitem__(key)
KeyError: 'bio'
我在views.py
class EmployeeAddView(generics.CreateAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
def post(self, request, format=None):
print(request.data)
designation = Group.objects.get(id=self.request.data['designation'],)
department = Group.objects.get(id=self.request.data['department'],)
bio = Bio.objects.get(id=self.request.data['bio'],)
employee = Employee.objects.create(
tax_id_number=request.data['tax_id_number'],
account_number=request.data['account_number'],
joining_date=request.data['joining_date'],
designation =designation,
department =department,
bio=bio,
)
return Response(status=status.HTTP_201_CREATED)
然后我创建了一个这样的序列化器:
# Nest Bio With User seriializer
class EmployeeSerializer(serializers.ModelSerializer):
# TODO: Define serializer fields here
bio = BioSerializer()
#user = UserSerializer()
class Meta:
model = Employee
# fields = ['user','tax_id_number','account_number','joining_date','designation','department','gender','marital_status','id_type','birthday','ethnicity','preferred_language','phone_number','em_contact','address']
fields = '__all__'
答案 0 :(得分:1)
在views.py文件中更新您的代码,如下所示
def post(self, request, format=None):
print(request.data)
designation = Group.objects.get(id=self.request.data.get('designation',None),)
department = Group.objects.get(id=self.request.data.get('department', None),)
bio = Bio.objects.get(id=self.request.data.get('bio', None),)
if designation and department and bio:
employee = Employee.objects.create(
tax_id_number=request.data['tax_id_number'],
account_number=request.data['account_number'],
joining_date=request.data['joining_date'],
designation =designation,
department =department,
bio=bio,
)
将行更新为bio = Bio.objects.get(id = self.request.data.get('bio',None),)如果缺少密钥或密钥为None值,则不会给您任何值,< strong>但它不会给你MultiValueDictKeyError。