简体   繁体   中英

Accessing django database from another python script

I have a Django project, and I need to access the information inside that database(model). This is my directory hierarchy-

在此处输入图像描述

I've seen a lot of questions on this subject, but everything I tried didn't work. For example-

import models
# gives me this error-

django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

If I try to do this I get another error-

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "OrAvivi.OrAvivi.settings")
import models
# gives me this error-
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

and it just continues...

I'm quite a newbie, spent most of my day on this so I would appreciate some help!

Okay, I found the BEST way EVER! import these modules-

import sqlite3
from sqlite3 import Error

Then, see what tables you have in your db and see the name of the table you want (you can do it here - enter link description here

And then just do this to see the information you have!

def create_connection():
    """ create a database connection to the SQLite database
        specified by the db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = sqlite3.connect(DB_PATH)
    except Error as e:
        print(e)

    return conn


def select_all_tasks(conn):
    """
    Query all rows in the tasks table
    :param conn: the Connection object
    :return:
    """
    cur = conn.cursor()
    cur.execute("SELECT * FROM to_excel_groups")

    rows = cur.fetchall()

    for row in rows:
        print(row)

This is how it looks in main():

DB_PATH = r'C:\Users\karin\PycharmProjects\Fiverr\OrAvivi\db.sqlite3'
conn = create_connection()
select_all_tasks(conn)

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