Updated March 16, 2023
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.
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:
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:
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:
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:
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:
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
We hope that this EDUCBA information on “SQLAlchemy Model” was beneficial to you. You can view EDUCBA’s recommended articles for more information.