2

I have written a python program which reads data from a directory of files and now I would like to save this data into a Django database. Ideally there would be a python script within my Django project which imports the necessary models reads the data and then writes to the database but I'm not sure if this is possible? If it is what imports do I need and where in the project directory would the script be saved?

2 Answers 2

1

You can save the file in root directory (where manage.py is present) of Django project and import your models as follows:

from django.core import management
from YourProject import settings
management.setup_environ(settings)

from YourApp.models import YourModel

Or try this code:

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "YourProject.settings")

from YourApp.models import YourModel
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the answer but I'm getting an error - AttributeError: 'module' object has no attribute 'setup_environ'
Which Django version are you using?
>>> django.VERSION (1, 6, 1, 'final', 0)
1

See the docs on custom management commands, which is by far the easiest way to do this.

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.