Django模型表输入

时间:2018-11-27 11:40:58

标签: python django

我正在尝试在当前项目中插入数据表。我想知道是否可以在一个特定的Django模型内插入整个表格。如果我让用户填写此表,例如下面的示例:

enter image description here

POST后如何将数据发送到模型中?

1 个答案:

答案 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的工具包)已经很好地涵盖了您所要求的功能。常规管道为:

  1. views.py中接收POST请求
  2. 使用您需要准备的模型serializer将请求数据转换为Python对象
  3. 将此对象保存在数据库中

所以视图可能看起来像这样(基于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教程,因为它涵盖了该主题。