Matheus Sant'ana
Matheus Sant'ana

Reputation: 593

Django Model Table Input

I am trying to insert a data table in my current project. I was wondering if it is possible to insert one whole table inside one particular Django Model. If I let the user fill this table, like in the example below:

enter image description here

How could I send that data into my model after POST?

Upvotes: 2

Views: 1993

Answers (1)

arudzinska
arudzinska

Reputation: 3331

As you stated in the comment under the question, your table has got fixed fields which should correspond to your already prepared database model - each table column is a separate model attribute. So the only thing you need to do is send each row input by the user as a separate entry in the JSON POST request which your code will convert into a model class instance and save it to the database. The JSON sent in the POST request could look something like this:

{    
    "table_entries": [
       {
           "sku": "22A",
           "name": "2B",
           "description": "2C",
           "price": "2D",
           "size": "2E"
       },
       {
           "sku": "3A",
           "name": "3B",
           "description": "3C",
           "price": "3D",
           "size": "3E"
       },
       ...
    ]
}

The functionality you're asking for is quite well covered in the Django REST Framework (DRF), a toolkit to build Web APIs. The general pipeline will be:

  1. Receive the POST request in views.py
  2. Use a model serializer that you need to prepare to convert the request data to a Python object
  3. Save this object in the database

So the views could look something like that (based on examples from the 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
        # ...

This is to show you the general workflow, because the question is quite broad. To go further into details I strongly advise to have a look into the DRF tutorial, as it covers well the topic.

Upvotes: 4

Related Questions