Gottfried
Gottfried

Reputation: 2139

Uploading Data from a Python File into a Django Database

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?

Upvotes: 2

Views: 228

Answers (2)

Prashant Borde
Prashant Borde

Reputation: 1178

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

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599460

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

Upvotes: 1

Related Questions