Need help for saving JSON object into Django Model (class object)

751 views
Skip to first unread message

Sonali Vighne

unread,
Sep 4, 2018, 8:22:22 AM9/4/18
to Django users
Hi,
I have create a model 

Models.py

from django.db import models
import datetime
from django.utils import timezone

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    def __str__(self):
        return self.question_text

    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

using this model table created in database. I am creating REST API . I am passing in request body

{
"question": { "question_text":"Some question?"
  "pub_date":timezone.now()
       }
}


I am getting this code, but how to save that data in existing model. So that I can save that info into database.
i.e. want to save above data question object.


RONAK JAIN

unread,
Sep 4, 2018, 9:37:06 AM9/4/18
to django...@googlegroups.com
hello Sonali

Please use:
python manage.py makemigrations
python manage.py migrate


Thanks
Ronak Jain

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/9fdae6df-dd1c-4229-b6eb-f8349528b1e0%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

pgopa...@gmail.com

unread,
Sep 4, 2018, 10:59:58 AM9/4/18
to Django users
# Please try to use this logic in your views.py file.
# first extract the data from the request 

question_text = request.data['question_text'] 
pub_date =  request.data['pub_date '] 

#Then store this data in your model.

Question.objects.create(question_text =question_text , pub_date = pub_date )

That's it. This will create an object in your data base with the data you extracted from the request. You can check in django admin panel.
Enjoy!


Sonali Vighne

unread,
Sep 5, 2018, 2:15:55 AM9/5/18
to Django users
Thanks I will try it.

Sonali Vighne

unread,
Sep 5, 2018, 4:14:32 AM9/5/18
to Django users
Thanks , it works for me. 
there is minor changes request.data is not working, so I tried request.body
and then extracted value from dict.

Do you know any other way to it without using dict.
if yes please , help with same.


On Tuesday, September 4, 2018 at 8:29:58 PM UTC+5:30, pgopa...@gmail.com wrote:
Reply all
Reply to author
Forward
0 new messages