Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a script to populate a django db

I want to run the following script to pre-populate a model of mine with names etc...But I get an error. The script is

first_names = first_names.split('\n')
last_names = last_names.split('\n')
phones=[str(i) for i in range(2310000000,2310999999, 1563)]
emails = ['test%[email protected]' %i for i in range(0,144)]

import os
os.environ['DJANGO_SETTINGS_MODULE']='project.settings'

from customer.models import Customer
from django.contrib.auth.models import User

users = User.objects.all()

if __name__ == "__main__":
    for i in range(10):
        customer = Customer(first_name=choice(first_names), last_name=choice(last_names),
                        telephone=choice(phones),email=choice(emails), creator=choice(users))
        customer.save()

and the error is

Traceback (most recent call last):
  File "populatedb.py", line 431, in <module>
    from customer.models import Customer
ImportError: No module named customer.models

the dir_tree is (if I can "draw" it correctly)

-project_dir
|
|--customer
|--|
   |--models.py(etc...)
|
|--project(the settings file is here)
|--
|--another_app
|--scripts (here is my python script)
like image 498
Apostolos Avatar asked Nov 26 '13 15:11

Apostolos


People also ask

How do I populate in Django?

To populate with Model instances, create a new Populator class, then list the class and number of all of Models that must be generated. To launch the actual data population, call `execute()` method.


1 Answers

You may append your sys path to your script like:

import sys
sys.path.append('/path/to/your/djangoproject/')

Hope this helps.

like image 173
Jingo Avatar answered Nov 01 '22 03:11

Jingo