[Fixed]-Trouble POSTing multiple related objects at once to api created with django rest framework

1👍

You need to make the todo_items in your serializer required = false. I am not sure I understand what your second issue is.

class NewToDoListSerializer(serializers.ModelSerializer):
room = serializers.PrimaryKeyRelatedField(many=False, read_only=False, queryset=Room.objects.all())
user = UserSerializer(read_only=True)
todo_items = CreateTodoItemSerializer(many=True, required=False)

class Meta:
    model = ToDoList
    fields = ['pk', 'slug', 'title', 'user', 'room', 'todo_items']
    lookup_field = "slug"
    depth = 1

def create(self, validated_data):
    todo_items_data = validated_data.pop('todo_items')
    todo_list = ToDoList.objects.create(**validated_data)
    for todo_item_data in todo_items_data:
        todo_item = ToDo.objects.create(user=todo_list.user, todo_list=todo_list, **todo_item_data)

Leave a comment