Answer the question
In order to leave comments, you need to log in
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,}}]
from djongo import models
class StaticForms(models.Model):
FormsID=models.ObjectIdField(primary_key=True)
make = models.JSONField()
static=models.JSONField()
day=models.JSONField()
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")
"make": {
"1_new": 21,
"2_new": 16,
"right": 80,
"left": 10,
},
"static": {
"name": " 1",
"number": 1,
"id":93}
"day": {
"start": 7,
"end": 23,}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question