Gardening App: Change to SQLAlchemy ORM

Rachela
1 min readAug 23, 2021

--

I am switching to the SQLAlchemy ORM from SQLAlchemy Core. This will be my second change as I started with SQL statements. The main reason is to connect the Gardens and Plants tables in the database. I would like for the user to be able to delete a garden and be given the option to delete all plants in that garden. It is also easier to filter results using the ORM, however, I had to make some changes in order to format the data for json. Here is some sample code:

from flask import Flask, request
from sqlalchemy import create_engine, Column, String, Integer, and_
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import json
engine = create_engine("postgresql+psycopg2://, echo=True)

Base = declarative_base()

app = Flask(__name__)


class Plants(Base):
__tablename__ = "plants"

id = Column(Integer, primary_key=True)
name = Column(String(length=50))
common_name = Column(String(length=50))
category = Column(String(length=50))
location = Column(String(length=50))
year = Column(Integer)
notes = Column(String(length=500))


class Gardens(Base):
__tablename__ = "gardens"

id = Column(Integer, primary_key=True)
name = Column(String(length=50))
notes = Column(String(length=500))


Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)
session = Session()


@app.route("/gardens", methods=["GET"])
def all_gardens():
results = session.query(Gardens).all()
garden_list = []
for result in results:
garden = {"id": result.id, "name": result.name, "notes": result.notes}
garden_list.append(garden)
return json.dumps(garden_list)


@app.route("/gardens/create", methods=["POST"])
def create_garden():
garden_name = request.form['name']
garden_notes = request.form['notes']
new_garden = Gardens(name=garden_name, notes=garden_notes)
session.add(new_garden)
session.commit()
return ''

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Rachela
Rachela

Written by Rachela

I am a librarian and new computer programmer creating an app with Python and Kivy to document the plants in my garden.

Responses (1)

Write a response