# Setup up the database

from BasicModelApp import db, Puppy  # Import db object and Puppy class

db.create_all()  # Create the tables in the database

sam = Puppy('Sammy', 3)  # Create new entries in the database
frank = Puppy('Frankie', 4)

print(sam.id)  # Check ids (Not added to the database so should be None)
print(frank.id)

db.session.add_all([
    sam, frank
])  # Ids will get created automatically once we add these entries to the DB

# db.session.add(sam)                   # Alternative for individual additions
# db.session.add(frank)

db.session.commit()  # Now save it to the database

print(sam.id)  # Check the ids
print(frank.id)
Beispiel #2
0
# Now that the table has been created by running
# BasicModelApp and SetUpDatabase we can play around with CRUD commands
# This is just an overview, usually we won't run a single script like this
# Our goal here is to just familiarize ourselves with CRUD commands

from BasicModelApp import db,Puppy

###########################
###### CREATE ############
#########################
my_puppy = Puppy('Rufus',5)
db.session.add(my_puppy)
db.session.commit()

###########################
###### READ ##############
#########################
# Note lots of ORM filter options here.
# filter(), filter_by(), limit(), order_by(), group_by()
# Also lots of executor options
# all(), first(), get(), count(), paginate()

all_puppies = Puppy.query.all() # list of all puppies in table
print(all_puppies)
print('\n')
# Grab by id
puppy_one = Puppy.query.get(1)
print(puppy_one)
print(puppy_one.age)
print('\n')
# Filters
#############################################################################
### NOTE!! If you run this script multiple times you will add ##############
### multiple puppies to the database. That is okay, just the ##############
### ids will be higher than 1, 2 on the subsequent runs ##################
#########################################################################

# Import database info
from BasicModelApp import db, Puppy

# Create the tables in the database
# (Usually won't do it this way!)
# this should not be in script but in command line
db.create_all()

# Create new entries in the database
sam = Puppy('Sammy', 3)
frank = Puppy('Frankie', 4)

# Check ids (haven't added sam and frank to database, so they should be None)
print(sam.id)
print(frank.id)

# Ids will get created automatically once we add these entries to the DB
db.session.add_all([sam, frank])

# Alternative for individual additions:
# db.session.add(sam)
# db.session.add(frank)

# Now save it to the database
db.session.commit()