答案 0 :(得分:1)
正如您在问题下的注释中所述,您的表具有固定的字段,这些字段应对应于您已经准备好的数据库模型-每个表列都是一个单独的模型属性。因此,您唯一需要做的就是将用户输入的每一行作为JSON POST请求中的单独条目发送,您的代码将转换为模型类实例并将其保存到数据库中。 POST请求中发送的JSON可能类似于以下内容:
{
"table_entries": [
{
"sku": "22A",
"name": "2B",
"description": "2C",
"price": "2D",
"size": "2E"
},
{
"sku": "3A",
"name": "3B",
"description": "3C",
"price": "3D",
"size": "3E"
},
...
]
}
Django REST Framework(DRF)(构建Web API的工具包)已经很好地涵盖了您所要求的功能。常规管道为:
views.py
中接收POST请求所以视图可能看起来像这样(基于DRF views docs的示例):
from myapp.models import Table
from myapp.serializers import TableSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
class TableView(APIView):
"""
Create a new entry in the Table.
"""
def post(self, request, format=None):
table_entries = request.data["table_entries"]
for entry in table_entries:
# serialize each row
serializer = TableSerializer(data=entry)
if serializer.is_valid():
# you can store the objects in some list and if the're all fine
# use serializer.save() for each of them to save them into the db
else:
# At least one of the entries data is corrupted. You probably want
# to reject the whole request
# ...
这是向您展示一般的工作流程,因为问题很广泛。为了进一步详细介绍,我强烈建议您查看DRF教程,因为它涵盖了该主题。