E
E
Enter_a_nickname2022-02-03 13:12:50
Django
Enter_a_nickname, 2022-02-03 13:12:50

How to correctly write json structure in models.py of django project using JSONField?

My project database is MongoDB, to connect mongo and django project (using version 4.0.1) I use "djОngo" engine. The database connection is working correctly.
I want to store data in MongoDB that is received from an external API or written through a form on a site page, which can have nested lists, or sometimes nested objects.
An example of a json structure that will be written through the form and come via the API:

"FormsID": 1,
"make": {
      "1_new": 21,
      "2_new": 16,
      "right": 80,
      "left": 10,
      },
   "static": [
      {
         "name": " 1",
         "number": 1,
         "id":93,
         "day": {
            "start": 7,
            "end": 23,}}]


At the moment, the task is partially implemented, I explain. My models.py file:

from djongo import models

class StaticForms(models.Model):
    FormsID=models.ObjectIdField(primary_key=True)
    make = models.JSONField()
    static=models.JSONField()
    day=models.JSONField()


Further, already in the views.py file, I add the necessary keys already in make, static and day.
My views.py file:

from django.views.decorators.csrf import csrf_exempt
from django.http.response import JsonResponse, HttpResponse
from FirstApp.models import StaticForms

@csrf_exempt
def forms_post(request):
    make = {"1_new":request.POST.get("1_new"),
                 "2_new":request.POST.get("2_new"),
                 "right":request.POST.get("right"),
                 "left":request.POST.get("left"),}

    static = {"name":request.POST.get("name"),
                 "number":request.POST.get("number"),
                 "id":request.POST.get("id")}

    day = {"start":request.POST.get("start"),
              "end":request.POST.get("end")}

    post = StaticForms(FormsID=request.POST.get("FormsID"),
                    make=make,
                    static=static,
                    day=day)
    post.save()
    return HttpResponse("Inserted")


After adding data via Postman, I get the following JSON structure. (different from required):
"make": {
      "1_new": 21,
      "2_new": 16,
      "right": 80,
      "left": 10,
      },
   "static": {
         "name": " 1",
         "number": 1,
         "id":93}
   "day": {
         "start": 7,
         "end": 23,}


1) How do I nest the dict "day" inside the dict "static" to get it like in my first example?
2) why is the "FormsID" field missing?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question