简体   繁体   中英

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.

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, eg

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM