1

我的应用名称是 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 创建的表中插入这个列表元素,并且在调用函数排序列表之后也是如此。该列表包含文件名及其计数。例如 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 #my project's name 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代码文件。请帮忙!!

/////////////////////////////////////////////////////////////////////////////////////////////////////////现在它给我这个错误help.see it at: 在 python 代码中访问在 django 中创建的表时出错

4

3 回答 3

1

It shouldn't be a probjem just importing your models and create object instances to persist to the database:

# 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()
于 2012-07-03T06:25:47.163 回答
1

For each element in your list, create an instance of Keywords_Search. After that, call .save() on each of them. For example:

for name, count in mylist:
    s = Keywords_Search(file_name=name, frequency_count=count)
    s.save()
于 2012-07-03T06:26:07.333 回答
0

首先,您的代码几乎没有问题(例如,您正在调用内置方法,更不用说count.__len__())。与其试图弄清楚你在做什么,这里有两种在 django 中推荐的方法:

  1. Django 提供了为SQL、XML、YAML 或 JSON 中的模型提供初始数据的功能。这允许您每次运行 syncdb 时自动插入数据。您不必再次运行命令。

  2. 创建一个自定义管理命令并运行它manage.py

我假设您有一个关键字文件,并且您想搜索文件中有多少输入的关键字。

以下是创建执行此操作的自定义管理命令的方法:

from collections import Counter
from django.core.management.base import BaseCommand, CommandError
from search.models import Keywords

class Command(BaseCommand):
    args = 'search_string'
    help = 'Enter the search string'


    def handle(self, *args, **options):
        file_contents = []
        with open('keyword_master.txt') as f:
            file_contents = [l for l in f.readlines() if l.rstrip('\n')]

        if not file_contents:
           raise CommandError("Cannot read keyword_master.txt")

        c = Counter(file_contents)

        for search_string in args:
            freq = c[search_string]
            Keywords.object.create(keyword=search_string,frequency_count=freq)
            self.stdout.write('Added %s freq for "%s"' % (freq,search_string))

commands在任何应用程序中创建一个名为的文件夹。在此文件夹中,创建一个名为__init__.py. 在同一文件夹中,将此文件另存为“keyword_importer.py”。所以现在你有:

/search
..__init__.py
../commands
.....__init__.py
.....keyword_importer.py
.....keyword_master.txt

现在运行它python manage.py keyword_importer mykeyword

于 2012-07-03T09:22:56.370 回答