我的应用名称是 search_keywords。在创建这个应用程序时,我将有一个名为 models.py 的文件 我在其中写了这篇文章,如果代码:
from django.db import models
class Keywords(models.Model):
file_name = models.CharField(primary_key=True, max_length=100)
frequency_count = models.IntegerField()
然后将此应用程序添加到 INSTALLED_APPS 并运行 python manage.py syncdb。在运行这个命令时,我会得到一个在 django 中自动创建的表。然后运行 python manage.py sql search_keywords。它将根据需要显示表格。
然后下一步是运行 python manage.py shell。我不想运行它,而是想将值插入通过我创建的 python 代码创建的表中。代码是:
#!/usr/bin/python
#here skey.py is another file created by me and has the imported functions
#in this code
from skey import find_root_tags, count, sorting_list
str1 = raw_input("enter the word to be searched\n")
list = []
fo = open("xml.txt","r")
for i in range(count.__len__()):
file = fo.readline()
file = file.rstrip('\n')
find_root_tags(file,str1,i)
list.append((file,count[i]))
sorting_list(list)
fo.close()
我想在 django 创建的表中插入这个列表元素,并且在调用函数 sorting_list 之后也插入这个列表元素。该列表包含文件名及其计数。例如list=[('books.xml','3'),('news.xml,'2')].
我该怎么做?
请帮助。
//////////////////////////////////////////////////////////////////////////
嘿,我已经写好了代码:
#!/usr/bin/python
#to tell django which settings module to use
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
from search.models import Keywords
from skey import find_root_tags, count, sorting_list
str1 = raw_input("enter the word to be searched\n")
list = []
fo = open("xml.txt","r")
for i in range(count.__len__()):
file = fo.readline()
file = file.rstrip('\n')
find_root_tags(file,str1,i)
list.append((file,count[i]))
sorting_list(list)
for name, count in list:
s = Keywords(file_name=name,frequency_count=count)
s.save()
fo.close()
这里 django_project = mysite #我的项目名称 and app = search #my app's name
运行此代码时出现错误:
追溯(最近的调用最后):
文件“call.py”,第 7 行,在
从search.models导入关键字
ImportError: 没有名为 search.models 的模块
以及包括:
import sys
sys.path.insert(0, path_to_django_project)
这在上面的代码中给出了错误:
追溯(最近的调用最后):
文件“call.py”,第 4 行,在
sys.path.insert(0,path_to_mysite)
NameError: 名称 'path_to_mysite' 未定义
为什么?我的桌面上有我的项目,还有上面的 python 代码文件。 请帮忙!!
/////////////////////////////////////// 现在它给了我这个错误,请帮助。在以下位置查看它: error in accessing table created in django in the python code
最佳答案
导入模型并创建对象实例以持久保存到数据库不应该是一个问题:
# setup sys.path first if needed
import sys
sys.path.insert(0, path_to_django_project)
# tell django which settings module to use
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'django_project.settings'
# import application models
import test_app.models as m
# create and save db entries...
o = m.TestObject()
o.var = 'spam'
o.par = 1
o.save()
关于python - 在 django 中不使用交互式 python shell 将值插入数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11305215/