this is my models.py file, i create Doctor model, Patient, Appointment to appointment both models doctor and patient:
#!/usr/bin/python3
from sqlalchemy.orm import declarative_base, relationship, sessionmaker
from sqlalchemy import Column, Integer, String, ForeignKey, create_engine, Table, Date
from datetime import datetime
engine = create_engine('mysql+pymysql://root:root@localhost:3306/medical') # to connect with DB
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
# Association table using ORM
class Appointment(Base):
__tablename__ = 'Appointments'
id = Column(Integer, primary_key=True)
doctor_id = Column(Integer, ForeignKey('doctors.id'))
patient_id = Column(Integer, ForeignKey('patients.id'))
appointment_date = Column(Date, default=datetime.utcnow)
doctor = relationship("Doctor", backref='Appointments')
patient = relationship("Patient", backref='Appointments')
def __repr__(self):
return f"<Appointment on {self.appointment_date}>"
class Doctor(Base):
__tablename__ = 'doctors'
id = Column(Integer, primary_key=True)
name = Column(String(50))
specialty = Column(String(50))
class Patient(Base):
__tablename__ = 'patients'
id = Column(Integer, primary_key=True)
name = Column(String(50))
dob = Column(Date)
Base.metadata.create_all(engine)
And this app.py file:
#!/usr/bin/python3
from models import Appointment, Doctor, Patient, engine
from sqlalchemy.orm import sessionmaker
from datetime import datetime
Session = sessionmaker(bind=engine)
session = Session()
dr_smith = Doctor(name="Dr. Smith", specialty="Cardiology")
mohamed_elhe = Patient(name="Mohammed Elhennawy", dob=datetime(2002, 2, 2))
appointment = Appointment(doctor=dr_smith, patient=mohamed_elhe)
# which is better:
# 1- session.add_all([appointment, mohamed_elhe, dr_smith])
# 2- session.add(appointment)
session.commit()
i know that add_all to add multiple objects to database, in this case, both ways works fine well.
But i need to make sure: is the second method the incorrect way to add?
New contributor
mohamed elhennawy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.