EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials SQL Tutorial SQLAlchemy Model
Secondary Sidebar
SQL Tutorial
  • SqlAlchemy
    • What is SQLAlchemy
    • SqlAlchemy ORM
    • SQLAlchemy count
    • SQLAlchemy update object
    • SQLAlchemy pip
    • SQLAlchemy Connection
    • SQLAlchemy Metadata
    • SQLAlchemy Raw SQL
    • SQLAlchemy Filter in List
    • SQLAlchemy Alias
    • SQLAlchemy unique
    • SQLAlchemy JSONB
    • SQLAlchemy Async
    • SQLAlchemy Types
    • SQLAlchemy Many to Many
    • SQLAlchemy Example
    • SQLAlchemy Model
    • SQLAlchemy Data Types
    • SQLAlchemy Filter
    • SQLAlchemy SQLite
    • SQLAlchemy DateTime
    • SQLAlchemy create_engine
    • SQLAlchemy Delete
    • SQLAlchemy Migrations
  • Basic
    • What is SQL
    • Careers in SQL
    • Careers in SQL Server
    • IS SQL Microsoft?
    • SQL Management Tools
    • What is SQL Developer
    • Uses of SQL
    • How to Install SQL Server
    • What is SQL Server
    • SQL Quick References
    • SQL Like Wildcard
    • SQL Like with Multiple Values
    • SQL Examples
    • SQL Server Versions
    • SQL DROP DB
    • SQL Case Insensitive
    • SQL Expressions
    • Database in SQL
    • SQL Data Types
    • SQL Keywords
    • Composite Key in SQL
    • SQL WAITFOR
    • SQL Constraints
    • Transactions in SQL
    • First Normal Form
    • SQL Server Data Types
    • SQL Administration
    • SQL Variables
    • SQL Enum
    • SQL GROUP BY WHERE
    • SQL ROW
    • SQL EXECUTE
    • SQL EXCLUDE
    • SQL Performance Tuning
    • SQL UUID
    • Begin SQL
    • SQL Update Join
    • Cheat sheet SQL
  • Operators
    • SQL Operators
    • SQL Arithmetic Operators
    • SQL Logical Operators
    • SQL String Operators
    • Ternary Operator in SQL
  • Commands
    • SQL Commands
    • sqlplus set commands
    • SQL Alter Command
    • SQL Commands Update
    • SQL DML Commands
    • SQL DDL Commands
    • FETCH in SQL
  • Clause
    • SQL Clauses
    • SQL IN Operator
    • SQL SELECT DISTINCT Multiple Columns
    • SQL Null Values
    • SQL LIKE
    • SQL LIKE Query
    • SQL LIKE Operator
    • SQL LIKE Clause
    • SQL NOT Operator
    • SQL Minus
    • SQL WHERE Clause
    • SQL with Clause
    • SQL HAVING Clause
    • SQL HAVING Clause
    • SQL GROUP BY DAY
    • ORDER BY Clause in SQL
    • SQL ORDER BY CASE
    • SQL ORDER BY DESC
    • SQL ORDER BY DATE
    • SQL ORDER BY Alphabetical
    • SQL ORDER BY Ascending
    • SQL Order by Count
    • SQL GROUP BY Month
    • SQL GROUP BY Multiple Columns
    • SQL GROUPING SETS
  • Queries
    • SQL Insert Query
    • SQL SELECT Query
    • SQL SELECT RANDOM
    • SQL Except Select
    • SQL Subquery
    • SQL SELECT DISTINCT
    • SQL WITH AS Statement
  • Keys
    • SQL Keys
    • SQL Foreign Key
    • Primary Key in SQL
    • Foreign Key in SQL
    • Unique Key in SQL
    • SQL UNIQUE Constraint
    • SQL Primary Key
    • Alternate Key in SQL
    • SQL Super Key
  • Functions
    • SQL Date Function
    • SQL Server Functions
    • SQL String Functions
    • SQL Compare String
    • Timestamp to Date in SQL
    • SQL REGEX
    • SQL Window Functions
    • SQL Syntax
    • SQL CONCAT
    • SQL ALTER TABLE
    • SQL MOD()
    • SQL Timestamp
    • SQL Min and Max
    • SQL TO_DATE()
    • SQL DATEADD()
    • SQL DATEDIFF()
    • SQL HOUR()
    • SQLite? functions
    • ANY in SQL
    • LIKE Query in SQL
    • SQL NOT NULL
    • SQL NOT IN
    • SQL MAX()
    • SQL MIN()
    • SQL SUM()
    • SQL COUNT
    • SQL identity
    • SQL DELETE Trigger
    • SQL Declare Variable
    • SQL Text Search
    • SQL COUNT DISTINCT
    • SQL TEXT
    • SQL Limit Order By
    • BETWEEN in SQL
    • LTRIM() in SQL
    • TOP in SQL
    • SQL Select Top
    • Merge SQL
    • SQL TRUNCATE()
    • SQL UNION
    • SQL ALL
    • SQL INTERSECT
    • SQL Alias
    • SQL Server Substring
    • CUBE in SQL
    • SQL RANK()
    • SQL CTE
    • SQL LAG()
    • SQL MID
    • SQL avg()
    • SQL WEEK
    • SQL DELETE
    • SQL DATEPART()
    • SQL DECODE()
    • SQL DENSE_RANK()
    • SQL NTILE()
    • SQL NULLIF()
    • SQL Stuff
    • SQL Ceiling
    • SQL EXISTS
    • SQL LEAD()
    • SQL COALESCE
    • SQL BLOB
    • SQL ROW_NUMBER
    • SQL Server Replace
    • SQL Ranking Function
    • SQL Server Permission
  • T-SQL
    • T-SQL pivot
    • T-SQL Formatter
    • T-SQL TRY CATCH
    • T-SQL CTE
    • T-SQL CASE
    • T-SQL DATEPART
    • T-SQL Date Format
    • T-SQL ROUND
    • T-SQL Loop
    • T-SQL IIF
    • T-SQL Union
    • T-SQL CREATE TABLE
    • T-SQL INSERT
    • T-SQL Stuff
    • T-SQL ISNULL
    • T-SQL ADD Column
    • T-SQL DATEDIFF
  • Joins
    • Join Query in SQL
    • Types of Joins in SQL
    • Types of Joins in SQL Server
    • SQL Inner Join
    • SQL Join Two Tables
    • SQL Delete Join
    • SQL Left Join
    • LEFT OUTER JOIN in SQL
    • SQL Right Join
    • SQL Cross Join
    • SQL Outer Join
    • SQL Full Join
    • SQL Self Join
    • Natural Join SQL
    • SQL Multiple Join
  • Advanced
    • MDF File in SQL Server
    • SQL Aliases
    • SQL Hosting
    • SQL Auto Increment
    • SQL Injection
    • SQL Wildcards
    • SQL Check
    • SQL Indexes
    • Select Distinct
    • SQL BETWEEN
    • SQLPlus spool
    • SQL Create Table
    • SQL Schema
    • Comparison Operators in SQL
    • SQL_plus
    • SQL Formatter
    • SQL LEFT INNER JOIN
    • SQL Plus Command
    • SQLPlus not found
    • SQL Injection Attack
    • Aggregate Functions in SQL
    • SQL REVOKE
    • SQL Select Distinct Count
    • IF ELSE Statement in SQL
    • SQL CASE Statement
    • SQL While Loop
    • SQL BIGINT
    • SQL Crosstab
    • SQL Wildcard Character
    • SQL INSTR()
    • SQL now
    • SQL synonyms
    • SQLite?export to csv
    • What is Procedure in SQL
    • Stored Procedure in SQL?
    • SQL Server Constraints
    • SQL DELETE ROW
    • Column in SQL
    • Table in SQL
    • SQL Virtual Table
    • SQL Merge Two Tables
    • SQL Table Partitioning
    • SQL Temporary Table
    • SQL Clone Table
    • SQL Rename Table
    • SQL LOCK TABLE
    • SQL Clear Table
    • SQL DESCRIBE TABLE
    • SQL Mapping
    • Cursors in SQL
    • AND in SQL
    • Wildcard in SQL
    • SQL FETCH NEXT
    • SQL Views
    • SQL Delete View
    • Triggers in SQL
    • SQL UPDATE Trigger
    • SQL AFTER UPDATE Trigger
    • SQL Update Statement
    • SQL DROP TRIGGER
    • SQL DROP Table
    • Types of SQL Views
    • SQL Port
    • SQL Clustered Index
    • SQL COMMIT
    • Distinct Keyword in SQL
    • PARTITION BY in SQL
    • SQL Set Operators
    • SQL UNION ALL
    • Metadata in SQL
    • SQL Bulk Insert
    • Array in SQL
    • SQL REGEXP
    • JSON in SQL
    • SQL For loop
    • EXPLAIN in SQL
    • ROLLUP in SQL
    • Escape Character SQL
    • SQL Cluster
    • SQL Backup
    • SQL Pattern Matching
    • SQL Users
    • ISNULL SQL Server
    • SQL pivot
    • SQL Import CSV
    • SQL if then else
    • SQL ignore-case
    • SQL Matches
    • SQL Search String
    • SQL Column Alias
    • SQL extensions
    • SQL Substring Function
    • Charindex SQL
  • NoSQL
    • NoSQL Databases List
    • NoSQL Data Modeling
    • Types of NoSQL Databases
    • NoSQL Injection
    • NoSQL vs SQL Databases
    • NoSQL Use Cases
    • NoSQL Key Value
  • Interview Questions
    • SQL Interview Questions
    • Advance SQL Interview Questions
    • SQL Joins Interview Questions
    • SQL Server Interview Questions
    • SQL Current Month

Related Courses

JDBC Training Course

PHP course

Windows 10 Training

SQL Course Training

PL/SQL Certification Courses

Oracle Certification Courses

SQLAlchemy Model

SQLAlchemy Model

Introduction to SQLAlchemy Model

The following article provides an outline for SQLAlchemy Model. SQLAlchemy models are how the database can be read and written in which everything being modeled is nothing but objects. The architecture assumed fundamentally for the models is the popular MVC, Model View Controller, which focuses on things. Any manipulation of any activity by the application leads to the modification and manipulation of the related objects. The examples we can consider arecial media applications; the database and applications deal with modeling the people on the platform.

All SQLAlchemy Model

We can understand the creation and maintenance of the model by following the below-mentioned steps:

Step 1: Base Model

The SQLAlchemy Models are written using one of the python libraries, such as Flask diamond, and represented using the SQLAlchemy. SQLAlchemy is considered one of the most potent libraries available, which can help work with databases. Here, the models are being saved and stored inside any of the databases, which makes the role of SQLAlchemy very crucial as t comes up with the essential features that make the work of getting the things done correctly.

Let us create a base model for the organization.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,354 ratings)

Code:

class Organization(db.Model, CRUDMixin):
id = db.Column(db.Integer, primary_key=True)
company_name = db.Column(db.String(255))
completed_years = db.Column(db.Integer)
originator_id = db.Column(db.Integer, db.ForeignKey('organization.id'))
originator = db.relationship('Organization',
main_connection=('Organization.originator_id == Organization.id'),
derived_connection="Organization.id")
tieup_company_id = db.Column(db.Integer, db.ForeignKey('organization.id'))
tieup_company = db.relationship('Organization',
main_connection=('Organization.tieup_company_id == Organization.id'),
derived_connection="Organization.id")
def __str__(self):
return self.company_name

Output:

SQLAlchemy Model 1

Step 2: Model Methods

Data models are created mainly when it is necessary to change the entities. Here, the product of model methods for manipulating the attributes of the entities becomes very helpful. For example, in maintaining the people’s data in social media apps, we can create a method named person’s birthday which helps increase the person’s age by 1.

It is essential to have the methods that cause altering the data inside the model. Also, ensure that all the processes responsible for manipulating data that involves insertion, removing, altering, or retrieval should be placed in model methods and given a call in the controller. Any technique directly dealing with the database in the controller should be removed and shifted to the model part. For the birthday method, the code can be written as shown below.

Code:

class Adult(db.Model, CRUDMixin):
person_id = db.Column(db.Integer, primary_key=True)
person_name = db.Column(db.String(255))
person_age = db.Column(db.Integer)
def its_birthday_time(samplePerson):
samplePerson.person_age += 1
samplePerson.save()

Output:

SQLAlchemy Model 2

Step 3: SQLAlchemy’s Relationship

The relationship patterns among objects in SQLAlchemy models may include one to one, one to many, many to one, many to many, and many to many associations.

For example, a company one too many relations with employees:

Code:

class Company(db.Model, CRUDMixin):
company_id = db.Column(db.Integer, primary_key=True)
company_addr = db.Column(db.String(255))
class Employee(db.Model, CRUDMixin):
company_id = db.Column(db.Integer, primary_key=True)
emp_name = db.Column(db.String(64))
company_company_id = db.Column(db.Integer, db.ForeignKey("company.company_id"))
company = db.relationship('Company',
backref=db.backref('persons', lazy='dynamic')
)

Now, we will use both classes to demonstrate how two employees belong to the same company, showing the relationship of one to many between company and employee.

Code:

educba = Company(company_addr="Sample in Mumbai, India")
emp1 = Employee("Aahana", company=educba)
emp2 = Employee("Mayur", company=educba)
print(emp1.company)

Output:

use of both the classes

Step 4: Querying using SQLAlchemy

For querying the data using SQLAlchemy, we can use the method below.

Models.name_of_model.find(constraint)

This retrieves the record for us. Also, we can use SQLAlchemy Query API, which is a compelling way of data retrieval and manipulation.

Example:

Code:

Models.Employee.find(emp_name = "Aahana")

Output:

SQLAlchemy Model 4

When change is made to Existing Model

When any change is made to the model, it’s evident that the associated table will also change. If a new attribute is added to the model, then a new column needs to be added to the table of the database as well. The two methods which help update the database include the clean state and schema migration.

In the clean state, the old database is straightly deleted. A new one is created with all the necessary changes taught, while the updates to be made in schema migration are analyzed. Then only the parts that are different from the old database are removed or added as per necessity which is a boon when your application and database are in production.

Benefits of using SQLAlchemy Model

  • SQLAlchemy provides the ORM, that is, object-relational mapper, which helps in reading and writing the data to the database, which is relatively easy to work with and access in the python files.
  • We can avoid some of the common pitfalls that can happen when we directly go for storing the data in SQL while making the use of SQLAlchemy.
  • Hence, it is essential to use SQLAlchemy, which prevents mismatches in the schema and SQL injections. SQLAlchemy models are beautifully explained in the official documentation of SQLAlchemy.

Create SQLAlchemy Model

  • The model may contain the following properties as the necessities, which include id, creation timestamp, and the update timestamp. There may be a necessity where we have to put some additional attributes and properties to the application and sometimes other methods that can be reused in the base model as per the requirement of your application. Still, the above properties can always be a kickstart for a model.
  • The parts of the base model include attributes and instance methods like update, delete and create, save and commit. The insertion of new objects into the model is done similarly. In case an error occurs then, the rollback to the previous state is also done in the same way because SQLAlchemy treats all the queries and performs it as a transaction which makes sure that a complete commitment of all the data updates is done or everything is rollbacked on the occurrence of error. The committing of the database is done by making use of the specification of the value of the commit.
  • The before insert and after insert methods of SQLAlchemy even allow you to customize the task of the save operation. The same is the case with forms of delete and update.
    The bulk_create method is a provision that makes the insertion of multiple rows in the database, from the array to dictionaries or collection to model instances.

Example of SQLAlchemy Model

Let us consider one example where we will have a class object named organization which will contain the id, name of the organization, and the completed years.

Code:

from flask.ext.diamond.utils.mixins import CRUDMixin
from .. import db
class Organization(db.Model, CRUDMixin):
id = db.Column(db.Integer, primary_key=True)
company_name = db.Column(db.String(255))
completed_years = db.Column(db.Integer)
originator_id = db.Column(db.Integer, db.ForeignKey('organization.id'))
originator = db.relationship('Organization',
main_connection=('Organization.originator_id == Organization.id'),
derived_connection="Organization.id")
tieup_company_id = db.Column(db.Integer, db.ForeignKey('organization.id'))
tieup_company = db.relationship('Organization',
main_connection=('Organization.tieup_company_id == Organization.id'),
derived_connection="Organization.id")
def __str__(self):
return self.company_name
from models import Organization
educba = Organization.create(company_name="EDUCBA", completed_years=34)
corporate_bridge = Organization.create(company_name="Corporate Bridge", completed_years=65)
educational_site = Organization.create(company_name="Educational_site", completed_years=64)
educba.originator = corporate_bridge
educba.tieup_company = educational_site
educba.save()
my_company = models.Organization.find(company_name="EDUCBA")
print(my_company.company_name)

Output:

class object named organization

The output gives my company object’s name, which was created as EDUCBA.

Conclusion

SQLAlchemy model is the model which is created by using the python libraries such as Flask diamond and makes the use of the SQLAlchemy as the database manager. It follows the transaction while performing any operation, ensuring that the task’s atomicity is achieved even if the error occurs or the mission is accomplished completely.

Recommended Articles

This is a guide to SQLAlchemy Model. Here we discuss the introduction, all SQLAlchemy models, benefits, and examples. You may also have a look at the following articles to learn more –

  1. SQL ORDER BY DESC
  2. SQL EXECUTE
  3. SQL EXCLUDE
  4. MySQL InnoDB Cluster
Popular Course in this category
JDBC Training (6 Courses, 7+ Projects)
  6 Online Courses |  7 Hands-on Projects |  37+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

PHP Training (5 Courses, 3 Project)4.9
Windows 10 Training (4 Courses, 4+ Projects)4.8
SQL Training Program (7 Courses, 8+ Projects)4.7
PL SQL Training (4 Courses, 2+ Projects)4.7
Oracle Training (14 Courses, 8+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more