mercredi 17 février 2016

How to Import objects

I use populate_core.py script to populate my sqlite database:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')

import django
django.setup()

from core.models import *

def populate():
    north = add_region('North')
    south = add_region('South')

def add_region(name):
    r = Region.objects.get_or_create(name=name)[0]
    r.save()
    return r

if __name__ == '__main__':
    print ("Starting Core population script...")
    populate()

Then I want to use populate_main.py script to add some data to the database:

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')

import django
django.setup()

from core.models import *
from populate_core import *

def populate1():
    dist_one = add_district('Dist_one', north)

def add_district(name, region):
    d = District.objects.get_or_create(name=name, region=region)[0]
    d.save()
    return d

if __name__ == '__main__':
    print ("Starting main population script...")
    populate1()

Both the scripts are in the project main directory (where is manage.py). When i run the first script it works but when I run the second scripts it give an error:

NameError: name 'north' is not defined

I think to be doing something wrong on the import line.

As alternative the 'north' object is in the database (db.sqlite3) so maybe I should look there?

Thank you for your help

Aucun commentaire:

Enregistrer un commentaire