Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing django database from python script

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.

like image 960
admfotad Avatar asked Sep 04 '17 19:09

admfotad


1 Answers

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)
like image 51
Chris Avatar answered Oct 16 '22 23:10

Chris