如何在没有表单的情况下将数据插入到django数据库中

时间:2014-04-19 08:11:53

标签: python django sqlite

您好我正在尝试将数据插入django中没有表单的数据库。

这是我的views.py文件

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`

这是我的url.py文件

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

这是我的models.py文件。我创建了两个表。并希望分别在两者中插入数据。

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`

我在控制台上获取输出。那个输出我要保存到数据库中。 Plz帮助。

谢谢..我尝试了其他方式。我收到的错误是:

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

我的代码:

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")`

4 个答案:

答案 0 :(得分:1)

您只想将数据保存到数据库,这样您就可以轻松地完成这项工作

>> 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')

或编写python脚本将数据导入数据库,将其放入项目目录,运行python manage.py shell然后import yourscript

如果您不喜欢python manage.py shell,只需设置DJANGO_SETTINGS_MODULE环境,然后在终端中运行python yourscript即可。如

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()

请记得将xxx替换为your app name

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

中国人可以在这里看到(其他人可以阅读代码):http://www.ziqiangxuetang.com/django/django-import-data.html

答案 1 :(得分:1)

问题解决了。答案如下。 将记录存储在django数据库中,而不使用任何输入或表单。 避免数据库中的重复条目。

这是我的views.py文件

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")

这是我的models.py文件。

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

答案 2 :(得分:0)

您可以使用Model.objects.create()

假设您正在接收来自邮政表格的数据,并希望保存在QuillModel中,这是在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})

有关保存到数据库的信息,请参见if request.method == "POST":部分。

答案 3 :(得分:0)

自从我做同样的事情。

例如:

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()

结论

您只需指定模型,然后使用您拥有的变量或列进行创建。

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

文件中的示例

12345678,good
12345678,bad