[Answered ]-To insert the values in database table without using interactive python shell in django

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

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

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

Leave a comment