SQLAlchemy ForeignKey Constraints
# SQLAlchemy-1.3.20
# pip install pymysql
from sqlalchemy import (create_engine, Float, Text, MetaData,
Table, Column, Integer, String, DateTime,
ForeignKey)
from datetime import datetime
meta_data = MetaData()
db_connection = 'mysql+pymysql://root:india@123@localhost/sql_alchemy'
# db_connection = 'mysql+pymysql://username:pasword@localhost/db_name'
#table = Model
users = Table('users', meta_data,
Column('user_id', Integer(), primary_key = True),
Column('username', String(15), nullable = False, unique = True),
Column('email', String(150), nullable = False),
Column('password', String(12), nullable = False),
Column('created_on', DateTime(),default=datetime.now,nullable = False),
Column('update_on', DateTime(), default=datetime.now, onupdate=datetime.now,nullable = False)
)
dish_items = Table('dish_items', meta_data,
Column('dish_id', Integer(), primary_key= True),
Column('rate', Float(),nullable = False, default = 1.0),
Column('name', String(100), nullable=False),
Column('recipe', Text(), nullable =True )
)
order = Table('order', meta_data,
Column('order_id', Integer(), primary_key = True),
Column('user_id', ForeignKey('users.user_id'),nullable = False),
Column('created_on', DateTime(),default=datetime.now,nullable = False),
)
bill = Table('bill', meta_data,
Column('bill_id', Integer(), primary_key = True),
Column('order_id', ForeignKey('order.order_id'), nullable = False),
Column('dish_id', ForeignKey('dish_items.dish_id'), nullable = False),
Column('bill_rate', Float(), nullable = False),
Column('quantity', Integer(), nullable = False)
)
engine = create_engine(db_connection)
try:
conn = engine.connect()
print('db connected')
print('connection object is :{}'.format(conn))
except:
print('db not connected')
meta_data.create_all(engine)
user_tom = users.insert().values(
username="tom",
email="tom@gmail.com",
password="12345",
)
user_jarry = users.insert().values(
username="jarry",
email="jarry@gmail.com",
password="12345",
)
dish_1 = dish_items.insert().values(
rate= 3.4,
name= 'Farm Fresh Pizza',
recipe= 'Onion, tomato, capsicum and mushroom.'
)
dish_2 = dish_items.insert().values(
rate= 2.4,
name= 'Cheese and Corn Pizza',
recipe= 'Corn and cheese.'
)
dish_3 = dish_items.insert().values(
rate= 4.4,
name= 'Spicy Paneer Pizza',
recipe= 'Sweet corn,jalapeno and red paprika.'
)
dish_4 = dish_items.insert().values(
rate= 3.4,
name= 'Veg Double Pizza Combo',
recipe= 'Onion and paneer,onion and capsicum,tomato and sweet corn,jalapeno and onion.'
)
# print(ins.compile().params)
result = conn.execute(user_tom )
result = conn.execute(user_jarry)
result = conn.execute(dish_1)
result = conn.execute(dish_2)
result = conn.execute(dish_3)
result = conn.execute(dish_4)
# print('Last inserted key:')
# print(result.inserted_primary_key)
Comments
Post a Comment