我是 python 新手,我有一个具有这种类型结构的 CSV 文件。上传后如何分割此 csv,并使用模型数据创建或更新我的 django 数据库。
About
no,name,shape,type
1,John,circle,metal
..................
..................
Address
no,street,postcode,city,County
1,peel,sd1 q23,london,east london
...............................
大约9个部分,一个主要的部分标题,在解析到数据库时可以忽略,第一行是标题,每列的数据
我能够创建一个模型并将数据从单行标题导入到我的模型中。我尝试使用
row.get('title')
来拆分 csv 文件,但它不起作用。我还找不到与此直接相关的任何示例。谢谢
所以我能够通过这样做来拆分 csv 文件并解析到我的 django 模型中:
def import_and_process_csv(请求): if request.method == 'POST':
data_set = ()
new_dataset = request.FILES['csv_file']
if not new_dataset.name.endswith('csv'):
messages.info(request,'wrong format')
return render(request,'import.html')
else:
messages.info(request, 'File uploaded successfully')
csv_content = new_dataset.read().decode('utf-8')
# Use io.StringIO to create a file-like object from the string content
csv_string_io = io.StringIO(csv_content)
next(csv_string_io)
data_set = csv.reader(csv_string_io, delimiter=',')
#Read the data for rows in store and parse into models.
specific_values = ['biscuit']
printed_rows_indices = set()
# Iterate over each specific value
for desired_value in specific_values:
# Initialize a flag to track if the desired row value is found
found_row_value = False
# Initialize a list to store rows before the desired value
rows_before_desired_value1 = []
for index, row in enumerate(data_set):
# Check if the desired value is found in the current row
if desired_value in row:
found_row_value = True
break
# Stop the CSV reader when the desired value is found
rows_before_desired_value1.append(row) #rows before Biscuit
next
for i,column in enumerate(rows_before_desired_value1):
if i !=0:
if column and not all(element == ',' for element in column): # Check if the list is not empty and not comma-only
if len(column) > 0:
myModel.objects.update_or_create(
My_Object1 = column[0],
My_Object2 = column[1],
)
return render(request,'import.html')