0

Hi I am trying to insert data to the database in django without forms.

This is my views.py file

def updatetrans(request):
    json_data=open('/home/ttt/Abc/a.json').read()
    data = json.loads(json_data)
    for pk, pv in data.iteritems():
    for k,v in pv.iteritems():
        try:
             print k, " =>> ", pv['transcript'][1]
        except:
            pass

This is my url.py file

url(r'^updatetrans/$', 'booki.account.views.updatetrans', name='updatetrans'),

Here is my models.py file. I have created two tables. And want to insert data in both of them separately.

class TransType(models.Model):
    name = models.TextField()
    def __unicode__(self):
        return self.name

class Trans(models.Model):
    trans = models.ForeignKey(TransType)
    script = models.CharField(max_length=200)
    def __unicode__(self):
        return self.trans

I am getting the output on console. That output I want to save to the database. Plz help.

Thank you.. I tried some other way. I am getting error as:

global name 'TransType' is not defined
Not inserted ==> e

My code:

def updatetrans(request):
    json_data=open('/home/ttt/Ali/a.json').read()
    data = json.loads(json_data)
    for pk, pv in data.iteritems():
        for k,v in pv.iteritems():
            try:
                trans_type = TransType.objects.get_or_create(name=k)
                trans = Trans()
                trans.trans_id = trans_type.id
                trans.script = pv[k][1]
                trans.save()
                print " Inserted ==>", pv[k][1]
            except Exception, e:
                print e
                print "Not inserted ==>", pv[k][1]
                pass
            return HttpResponse("Done")
8
  • Should we assume your json data matches the database structure? Commented Apr 19, 2014 at 8:15
  • The output of the json data is: transcript =>> is that ok? you are not measuring it here. so you can say measure that also, but that we do in Feed Forward control. transcript =>> In fact i wanted to write down the Mass Balance Equation explain =>> we assume that we measure it. of course, we can measure x also, transcript =>> we assume that we measure it. of course, we can measure x also. The name field should contain: transcript, explain. The trans should contain the same. And the script should contain the ==> text. I am newbie. Based on key values can we store? Commented Apr 19, 2014 at 8:23
  • I have no idea what you're trying to say. That doesn't look like JSON to me. was something lost when you tried to paste it? Maybe try pasting your json on dpaste.org Commented Apr 19, 2014 at 8:32
  • Post the raw json, please Commented Apr 19, 2014 at 8:33
  • I have extracted values from json file. plz check the view.py file. I want to insert those extracted values in db. Commented Apr 19, 2014 at 8:36

4 Answers 4

4

The problem is solved. The answer is as follows. To Store the records in the django database without using any input or form. To avoid duplicate entries in the database.

This is my views.py file

def updatetrans(request):
      json_data=open('/home/ttt/Ali/a.json').read()
      data = json.loads(json_data)
      for pk, pv in data.iteritems():
            for k,v in pv.iteritems():
                  try:
                        trans_type = TransType.objects.get_or_create(name=k)
                        trans = Trans()
                        trans.transtype_id = trans_type[0].id
                        if isinstance(pv[k], basestring):
                              script = pv[k]
                        else:
                              print "****** List ****"
                              script = pv[k][1]
                        trans.script = script
                        trans.save()
                        print " Inserted ==>", script
                  except Exception, e:
                        print e
                        #print "Not inserted ==>", pv[k][1]
                        pass
      return HttpResponse("Done")

This is my models.py file.

class TransType(models.Model):
      name = models.TextField()
      created = models.DateTimeField(auto_now_add = True)
      updated = models.DateTimeField(auto_now = True) 
      def __unicode__(self):
          return self.name

class Trans(models.Model):
      transtype = models.ForeignKey(TransType)
      script = models.CharField(max_length=200)
      created = models.DateTimeField(auto_now_add = True)
      updated = models.DateTimeField(auto_now = True) 
      class Meta:
            unique_together = (("transtype", "script"),)
      def __unicode__(self):
          return self.trans
Sign up to request clarification or add additional context in comments.

Comments

2

You just want to save data to database, so you can do it like this easily

>> cd project_directory
>> python manage.py shell
>> from xxx.models import TransType,Trans
>> tt = TransType.objects.create(name='read from file')
>> Trans.objects.create(trans=tt, script='read from file')

or write a python script to import data to database, put it in your project directory,run python manage.py shell then import yourscript

if you don't like python manage.py shell, just set DJANGO_SETTINGS_MODULE environment, then just run python yourscript in terminal. Such as

import os
os.environ["DJANGO_SETTINGS_MODULE"] =  "yoursite.settings"

# The above two lines could be written simply as:
# from project.wsgi import *

from xxx.models import import TransType,Trans
TransType.objects.create()
Trans.objects.create()

remember to replace xxx with your app name

see QuerySet API:https://docs.djangoproject.com/en/dev/ref/models/querysets/#create

Chinese people could see here (other people could just read the code): http://www.ziqiangxuetang.com/django/django-import-data.html

1 Comment

Thank you.. I tried some other way. I am getting error.
1

You can do it using Model.objects.create()

Let's say you're receiving data from post form and want to save in QuillModel, here's how to do it in python2 django

from __future__ import unicode_literals

from django.http import HttpResponse
from django.shortcuts import redirect, render

from .forms import TemplateForm

from .models import QuillModel

def app3(request):
    if request.method == "POST":
        print(request.POST)
        html_content = request.POST.get('html_content')
        input_area = request.POST.get('input_area')

        if html_content and input_area:
            obj = QuillModel.objects.create(html_content=html_content, input_area=input_area)
            obj.save()

        return redirect('/app3/app3')

    else:
        form = TemplateForm()
        return render(request, 'app3/forms/f1_post_form.html', {'form' : form})

See the if request.method == "POST": part for saving into database.

Comments

0

Since I have been doing the same thing..

For example:

models.py

class Dataset(models.Model):
    hash = models.CharField(max_length=32)
    category = models.CharField(max_length=10)

views.py

 if request.method == "POST":
    uploaded_file = request.FILES['document']
    fs = FileSystemStorage()
    fs.save(uploaded_file.name,uploaded_file)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    media_path = os.path.join(BASE_DIR,'dataset')
    full_path=os.path.join(media_path,uploaded_file.name)
    f = default_storage.open(full_path, 'r')
    data = f.read()
    for i in data.split("\n"):
        hash,category = i.strip("\n").split(",")
        Dataset.objects.create(hash=hash,category=category)
        print("yes")
    f.close()

Conclusion

You just specify your models and then create with what variable or column that you have.

MODELS.objects.create(column1=data1,column2=data2)

Example inside of my file

12345678,good
12345678,bad

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.