What do I need to import to gain access to my models?

I'd like to run a script to populate my database. I'd like to access it through the Django database API.

The only problem is that I don't know what I would need to import to gain access to this.

How can this be achieved?

Asked by: Daisy708 | Posted: 27-01-2022

Answer 1

Import your settings module too

import os
os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings"

from mysite.polls.models import Poll, Choice

should do the trick.

Answered by: Daryl789 | Posted: 28-02-2022

Answer 2

This is what I have at the top of one my data loading scripts.

import string
import sys
    import settings # Assumed to be in the same directory.
except ImportError:
    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)

#Setup the django environment with the settings module.
import django
import django.core.management

from django.db import transaction

This should all execute before you do much else in your script.

Another method is to use fixtures and manage.py. Though if you are just trying to accomplish a bulk data load to initialize a database this should work fine.

Also depending on what you are doing you may or may not want to do it all in one transaction. Uncomment the transaction line above and structure your code similar to this.

    #Do some stuff

Answered by: Roman272 | Posted: 28-02-2022

Answer 3

If you use the shell argument to the manage.py script in your project directory, you don't have to import the settings manually:

$ cd mysite/
$ ./manage.py shell
Python 2.5.2 (r252:60911, Jun 10 2008, 10:35:34) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from myapp.models import *

For non-interactive use you could implement a custom command and run it with manage.py.

Answered by: Adrian887 | Posted: 28-02-2022

Answer 4

The cleanest solution is to add django extensions.

(virt1)tsmets@calvin:~/Documents/prive/rugby-club/proposal/kitu$ yolk -l
Django          - 1.3.1        - active 
Pygments        - 1.4          - active 
Python          - 2.6.5        - active development (/usr/lib/python2.6/lib-dynload)
django-extensions - 0.7.1        - active 
pip             - 1.0.2        - active 
setuptools      - 0.6c11       - active 
wsgiref         - 0.1.2        - active development (/usr/lib/python2.6)
yolk            - 0.4.1        - active 

The list of possible commands is then extended with among other things the runscript command.

Answered by: Elise403 | Posted: 28-02-2022

Answer 5

In addition to your own models files, you need to import your settings module as well.

Answered by: Wilson404 | Posted: 28-02-2022

Similar questions

python - from x import y - access name of x?

Quick question: from x import y, z Is there any way that I can access the name of x within the script? I know that if I look at the locals() or globals() dict, that I can see y and z, but I can't seem to find a way to look for x.

python - How to import csv and access table data?

I am attempting to import a csv file (test.csv) using pandas read_table() and then assign each of the columns to a new variable. test.csv contains the following: a,b,c 1,2,3 1,2,3 1,2,3 I am able to import the data as a table and print it to the console. However, I am unable to assign columns to variables.

Python 3.0 Import Excel file to Access File

I have used Python 3 to create an Excel (.xlsx) file. Now I want to convert this Excel file to an Access (.accdb) file. I know Access can import Excel file, but I am trying to use Python to automate this. There are 3 sheets in the Excel file. I have made a connection between Excel and Access but not sure how to insert the sheets/values in the Access file. Thank you so much for your help! Many Thanks!

Python import coding style

I've discovered a new pattern. Is this pattern well known or what is the opinion about it? Basically, I have a hard time scrubbing up and down source files to figure out what module imports are available and so forth, so now, instead of import foo from bar.baz import quux def myFunction(): foo.this.that(quux) I move all my imports into the function where they're actually used...

ds python import math module

I'm trying to get some python code I've written earlier on Windows to work on my DS. I'm using (DSPython), and when I tried to import math, it failed with "ImportError: No module named math". I've gotten most all other modules I need that don't rely on math working. But math is normally a builtin module, so I can't just find math.py on my PC and...

Python - import error

I've done what I shouldn't have done and written 4 modules (6 hours or so) without running any tests along the way. I have a method inside of /mydir/__init__.py called get_hash(), and a class inside of /mydir/utils.py called SpamClass. /mydir/utils.py imports get_hash() from /mydir/__init__. /mydir/__in...

Python "import" scope

I am dealing with some python code automatically generated for me. I want to avoid manually editing these python files & hence this question/issue: foo.py: def foo(): print "foo" boo.py: def boo(): foo.foo() # <-- global name 'foo' not defined print "boo" bar.py: import foo import boo def b...

python - Why import when you need to use the full name?

In python, if you need a module from a different package you have to import it. Coming from a Java background, that makes sense. import foo.bar What doesn't make sense though, is why do I need to use the full name whenever I want to use bar? If I wanted to use the full name, why do I need to import? Doesn't using the full name immediately describe which module I'm addressing? It ju...

Python : How to import a module if I have its path as a string?

Lets say I have path to a module in a string module_to_be_imported = 'a.b.module' How can I import it ?

Python import error: no module named

I am very new at Python. I have an existing example project that has the scripts YYY in path XXX/YYY, and a script A.py that call these one by one. I only want to add a script ZZZ.py to the YYY scripts so that call after them. I add this script in the same path (XXX/ZZZ.py) and try to import it in the A.py and call it.

python - Import error in django

I am trying to understand how the django multilanguage feature works and I found this example What I have done is created a test project and included that in settings.py In the test directory I have multilingual.py and models.py (available at the link above). But when I run python manage.py in the shell I ge...

python - import pyodbc results in DLL load failed with error code 193 on Win7

I am running 64-bit Windows 7 and the ActiveState Python 2.5 installation (64-bit version). I just downloaded and installed the pyodbc 2.1.7 win32 package. When I run the installer as an admin it proceeds with no problem. When I run python and try import pyodbc I receive the following error: ImportError: DLL load failed with

python - Why can't I import pygtk?

I followed the instructions in this post. Everything installed successfully. However, when I run python I cannot import pygtk. Specifically, it says this: >>> import pygtk \n “ImportError: No module named pygtk” I'm guessing I have to do some commands like make or s...

python - What's the best Django search app?

How can I use a DLL file from Python?

What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.

python - PubSub lib for c#

Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.

python - What is the best way to copy a list?

This question already has answers here:

python - Possible Google Riddle?

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...

How do you check whether a python method is bound or not?

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?

ssh - How to scp in Python?

What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...

python - How do I create a new signal in pygtk

I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

python - How do I edit and delete data in Django?

I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...

python - How do I turn an RSS feed back into RSS?

According to the feedparser documentation, I can turn an RSS feed into a parsed object like this: import feedparser d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml') but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XM...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python