# how to run python/djanjo shell as a script

**URL:** <https://forum.djangoproject.com/t/how-to-run-python-djanjo-shell-as-a-script/5424>\
**Category:** Using Django\
**Created:** [November 28, 2020, 12:20am UTC](https://forum.djangoproject.com/t/how-to-run-python-djanjo-shell-as-a-script/5424 "2020-11-28T00:20:55Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![rssail](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/rssail/32/2407_2.png) [@rssail](https://forum.djangoproject.com/u/rssail)\
**Post date:** [November 28, 2020, 12:20am UTC](https://forum.djangoproject.com/t/how-to-run-python-djanjo-shell-as-a-script/5424/1 "2020-11-28T00:20:55Z")

</div>

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()

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 28, 2020, 1:20am UTC](https://forum.djangoproject.com/t/how-to-run-python-djanjo-shell-as-a-script/5424/2 "2020-11-28T01:20:00Z")

</div>

What you’re probably looking for are [Django management commands](https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/#module-django.core.management). They give you the ability to use the ORM, from within a script.

---

<div class="post-metadata">

**Author:** ![rssail](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/rssail/32/2407_2.png) [@rssail](https://forum.djangoproject.com/u/rssail)\
**Post date:** [November 28, 2020, 1:44am UTC](https://forum.djangoproject.com/t/how-to-run-python-djanjo-shell-as-a-script/5424/3 "2020-11-28T01:44:09Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 28, 2020, 2:15am UTC](https://forum.djangoproject.com/t/how-to-run-python-djanjo-shell-as-a-script/5424/4 "2020-11-28T02:15:23Z")

</div>

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.
