当我尝试调用POST方法时,它成功创建,但是在序列化程序中收到错误消息。当我在RESTful API中调用此方法时,应该怎么做才能获得成功?
Serializers.py:
def create(self, validated_data):
if 'branches' in validated_data:
branches_data = validated_data.pop('branches')
if 'contacts' in validated_data:
contacts_data = validated_data.pop('contacts')
course = Course.objects.create(**validated_data)
branches_list = []
contacts_list = []
print(contacts_data)
print(branches_data)
for branches_details in branches_data:
branches_list.append(Branch.objects.create(
course_id = course.id,
**branches_details))
for contacts_details in contacts_data:
contacts_list.append(Contact.objects.create(
course_id = course.id,
**contacts_details))
course.save()
return course
答案 0 :(得分:1)
我将假设branches_data
和contacts_data
是列表,因此,如果它们不存在,则应将它们声明为空列表。将运行以下代码:
def create(self, validated_data):
branches_data = validated_data.pop('branches') if 'branches' in validated_data else []
contacts_data = validated_data.pop('contacts') if 'contacts' in validated_data else []
course = Course.objects.create(**validated_data)
branches_list = []
contacts_list = []
print(contacts_data)
print(branches_data)
for branches_details in branches_data:
branches_list.append(Branch.objects.create(
course_id = course.id,
**branches_details))
for contacts_details in contacts_data:
contacts_list.append(Contact.objects.create(
course_id = course.id,
**contacts_details))
course.save()
return course