当我在RESTful API中请求POST方法时,我的course_id
中的BranchSerializer
有问题。
所有答案都提前感谢!
代码示例serializers.py
:
class BranchSerializer(serializers.ModelSerializer):
class Meta:
model = Branch
fields = ('address', 'latitude', 'longitude')
class ContactSerializer(serializers.ModelSerializer):
class Meta:
model = Contact
fields = ('type', 'value')
class CourseSerializer(serializers.ModelSerializer):
branches = BranchSerializer(many=True, required=False)
contacts = ContactSerializer(many=True, required=False)
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
Models.py:
class Branch(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name="branches")
latitude = models.TextField()
longitude = models.TextField()
address = models.TextField()
def __str__(self):
return str(self.address)
没有NULL约束失败:courses_app_branch.course_id