9

I'm trying to access my Django database from within a regular Python script. So far what I did is:

import os
import django
from django.db import models

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "m_site.settings")
django.setup()

from django.apps import apps
ap=apps.get_model('py','Post')

q=ap.objects.all()

for a in q:
    print(a.title)

There is an application in Django called py where I have many posts (models.py, which contains class Post(models.Model)).

I would like to have the possibility to access and update this database from a regular Python script. So far script above works fine, I can insert, update or query but it looks like it is a separate database and not the database from Django's py application. Am I doing something wrong or missing something? Any help would be very appreciated.

6
  • 1
    The code above should use the DATABASES configuration from your m_site.settings module. Commented Sep 4, 2017 at 19:56
  • Do you know how to properly read databases configuration from django and then get objects from specified app ? Commented Sep 5, 2017 at 6:34
  • The code you have shown should access the database defined in DATABASES in m_site.settings. You don't have to read the configuration manually, so asking "how to properly read databases configuration" doesn't really make sense. We can't really help any further, because you haven't said what DATABASES in m_site.settings is, or which database you wish to connect to. Commented Sep 5, 2017 at 8:37
  • Sure, I,ve forgot to say it is default db: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Commented Sep 5, 2017 at 9:36
  • It sounds like os.path.join(BASE_DIR, 'db.sqlite3') doesn't point to the correct sqlite file. Commented Sep 5, 2017 at 9:43

1 Answer 1

14

Consider writing your script as a custom management command. This will let you run it via manage.py, with Django all properly wired up for you, e.g.

python manage.py print_post_titles

Something like this should be a good start:

from django.core.management.base import BaseCommand
from py.models import Post

class Command(BaseCommand):
    help = 'Prints the titles of all Posts'

    def handle(self, *args, **options):
        for post in Post.objects.all():
            print(a.title)
Sign up to request clarification or add additional context in comments.

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.