1

My app name is search_keywords. As on creating this app, I wiil have one file called models.py in which I have written this piece if code :

from django.db import models 

class Keywords(models.Model):
    file_name = models.CharField(primary_key=True, max_length=100)
    frequency_count = models.IntegerField()

then add this app to INSTALLED_APPS and run python manage.py syncdb. On running this command , I will get a table automatically created in django. Then run python manage.py sql search_keywords. It will show the table as desired.

Then the next step is to run python manage.py shell.Instead of running this I want to insert the values in my table created through the python code that I have created.The code is:

#!/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()

I want to insert this list elements in the the table created by the django and that too after the function sorting_list has been called. The list contains the file name and it's count. e.g. list=[('books.xml','3'),('news.xml,'2')].

How can I do that?

Please Help.

//////////////////////////////////////////////////////////////////////////////

Hey I have written the code:

#!/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()

Here django_project = mysite #my project's name and app = search #my app's name

on running this code it gives me error :

Traceback (most recent call last):

File "call.py", line 7, in

from search.models import Keywords

ImportError: No module named search.models

and on including :

import sys
sys.path.insert(0, path_to_django_project)

this in above code it gives error:

Traceback (most recent call last):

File "call.py", line 4, in

sys.path.insert(0,path_to_mysite)

NameError: name 'path_to_mysite' is not defined

Why?I have my project on the desktop and the above python code file as well. Please Help!!

////////////////////////////////////////// now it's giving me this error , please help.see it at : error in accessing table created in django in the python code

2
  • hey there is no-one who can help me at this . please guys I really need to know urgently . please help!!! Commented Jul 3, 2012 at 6:20
  • please someone help me at the second problem that I mentioned half hour ago. Commented Jul 3, 2012 at 8:58

3 Answers 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()
Sign up to request clarification or add additional context in comments.

4 Comments

please tell me one more thing that the code you have given import os os.environ['DJANGO_SETTINGS_MODULE'] = 'django_project.settings', I have to write these lines in my code mentioned above.
if you want to use django from a pyhton script outside of a django app, yes, you'll have to set it up first so django can find the configuration, and the directory of the django project must be in sys.path. more here
can you please look at my code that I have just edited and mentioned above. why is it giving such error?
Just replace path_to_mysite with the path to your project directory. It's complaining that the variable isn't set.
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()

1 Comment

can you please look at my code that I have just edited and mentioned above. why is it giving such error?
0

First, there are few problems with your code (for example, you are calling methods that are built-ins, not to mention count.__len__()). Instead of trying to figure out what you are doing, here are the two recommended way to do this in django:

  1. Django provides the functionality to provide initial data for models in SQL, XML, YAML or JSON. This allows for automatic data insertion everytime you run syncdb. You don't have to run a command again.

  2. Create a custom management command and run it with manage.py

I'm assuming you have a file of keywords, and you want to search how many of the entered keyword is in the file.

Here is how you would create a custom management command that does this:

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

Create a folder called commands inside any app. Inside this folder, create a blank file called __init__.py. In the same folder, save this file as "keyword_importer.py". So now you have:

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

Now run it with python manage.py keyword_importer mykeyword

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.