how to run python/djanjo shell as a script

In a tutorial on django we create a simple table run migrations and then go into a shell with the command:

python manage.py shell

from there, in the shell we run the following:

from flights.models import Flight
f = Flight(origin=“New York”, destination=“london”, duration=415)
f.save()

I’m trying to figure out how to run these commands from a py file so I created test.py:

from flights.models import Flight
f=Flight(origin=“New York”,destination=“London”, duration=415)
f.save()

but get the error Models aren’t loaded. How to resolve? I’m definitely a little confused.

I am able to update the database from a web served page with the following in my views.py file:

from django.shortcuts import render

from flights.models import Flight

def index(request):
f=Flight(origin=“New York”,destination=“London”, duration=415)
f.save()
return render(request, “flights/index.html”, {

})

What I am asking is how to update the database directly on the backend. Do I just use standard python sql commands? For instance:

import sqlite3
from sqlite3 import Error
import csv

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

return conn

def sql_create(conn, create_table_sql):
“”" create a table from the create_table_sql statement
:param conn: Connection object
:param create_table_sql: a CREATE TABLE statement
:return:
“”"
try:
c = conn.cursor()
c.execute(create_table_sql)
except Error as e:
print(e)

def sql_insert(conn,sql,data,single):
cur=conn.cursor()
if single:
cur.execute(sql,data)
rowCount = cur.lastrowid
else:
cur.executemany(sql,data)
rowCount = cur.rowcount

conn.commit()
return(rowCount)

def sql_select(conn,sql,data):
cur = conn.cursor()
cur.execute(sql,data)
rows = cur.fetchall()
return rows

def sql_update(conn,sql,data):
cur = conn.cursor()
cur.execute(sql,data)
conn.commit()

def sql_delete(conn,sql,mydata):
print(mydata)
cur = conn.cursor()
cur.execute(sql,mydata)
conn.commit()

def main():
insert = False
db_file = r"/home/saltydog/Database/crud.db"

# create a database connection
conn = sql_connection(db_file)

# create tables
sql_create_price_table = """ CREATE TABLE IF NOT EXISTS prices (
                                    ticker text NOT NULL,
                                    ymd integer,
                                    price real,
                                    PRIMARY KEY(ticker,ymd)
                                ); """

sql_create_price2_table = """ CREATE TABLE IF NOT EXISTS prices2 (
                                    ticker text NOT NULL,
                                    ymd integer,
                                    price real,
                                    PRIMARY KEY(ticker,ymd)
                                ); """


if conn is not None:
    # create projects table
    sql_create(conn, sql_create_price_table)
    sql_create(conn, sql_create_price2_table)
    conn.commit()

else:
    print("Error! cannot create the database connection.")

if(insert):
    sql_insert_record = """insert into prices(ticker,ymd,price)
                           values(?, ?, ?)"""

    cnt = 0
    with open('ibm.txt') as f:
        reader = csv.reader(f)
        for row in reader:
            ticker = row[0]
            ymd = row[1]
            price = row[2]
            data = (ticker, ymd, price)
            if cnt != 0:
                rowid = sql_insert(conn,sql_insert_record,data,True)
                print(rowid)
            cnt+=1

    sql_insert_records = """insert into prices2(ticker,ymd,price)
                            values(?, ?, ?)"""

    data=[]
    cnt=0
    with open('ibm.txt') as f:
        reader = csv.reader(f)
        for row in reader:
            ticker = row[0]
            ymd = row[1]
            price = row[2]
            if cnt != 0:
                data.append((ticker, ymd, price))
            cnt+=1

    rowid = sql_insert(conn,sql_insert_records,data,False)
    print(rowid)

select_records = """select ticker,ymd,price from prices
                        where ticker = ?
                        group by price
                        order by price"""

data=('IBM', )
rows = sql_select(conn,select_records,data)
for row in rows:
    print(row)


select_records = """select ticker,ymd,price from prices
                        where ticker = ?
                        and price > ?"""

data=('IBM',100.0)
rows = sql_select(conn,select_records,data)
for row in rows:
    print(row)



select_records = """select ticker,ymd,price from prices
                        where ymd = ?"""

data=(19990527, )
rows = sql_select(conn,select_records,data)
for row in rows:
    print(row)


sql_update_records = """update prices
                        set price = ?
                        where ymd = ?"""

data = (200.00,19990527)
sql_update(conn,sql_update_records,data)


sql_delete_record = """delete from prices where ymd = ?"""
mydata = (19990528, )
sql_delete(conn,sql_delete_record,mydata)

if name == ‘main’:
main()

What you’re probably looking for are Django management commands. They give you the ability to use the ORM, from within a script.

that’s great, thank you. So, is there a problem if I update the database directly with sql?

No, there’s not necessarily a problem, you’re just creating a lot of unnecessary work for yourself. There is the possibility that by bypassing logic that you have implemented for your models, you may introduce data inconsistencies with your application, but with a little bit of care you can avoid that.

1 Like