DEV Community

victor wangari
victor wangari

Posted on

OBJECT-RELATIONAL MAPPING in PYTHON

KEY VOCAB
Object-Relational Mapping(ORM): A technique used to convert database records into objects in an object-oriented language.

INTRODUCTION
**Object Relational Mapping is way for our python programs to manage database data by "mapping" database tables to classes and instances of classes to rows in those tables.
**There is no special programming magic to an ORM ā€” it is simply a manner in which we implement the code that connects our Python program to our database. For example, you can use code like this to connect your Python program to a given database:

*db_connection = sqlite3.connect('db/my_database.db')
db_cursor = db_connection.cursor()
*

An ORM is really just a concept. It is a design pattern , a conventional way for us to organize our program when we want those programs to connect to a database.The conventional is this :
When "mapping" our program to a database, we equate classes with database tables, and instances of those classes with table rows.

WHY USE ORM??
.Cutting down repetitive code.
.Implementing conventional patterns that are organized and sensical

Cutting Down on Repetition
As programmers , you might remember we are lazy.We don't like to repeat ourselves if we can avoid it. Repetition qualifies as a "code smell". Instead of repeating the same, or similar, code any time we want to perform common actions against our database, we can write a series of methods to abstract that behavior.
** We can use **save()
method on our classes that handles the common actions if INSERTing data into database.

LOGICAL DESIGN
**Another important reason to implement the ORM pattern is that it just makes sense. Telling our Python program to communicate with our database is confusing enough without each individual developer having to make their own, individual decision about how our program should talk to our database.

Instead, we follow the convention: classes are mapped to or equated with tables and instances of a class are equated to table rows.

If we have a Cat class, we have a cats table. Cat instances get stored as rows in the cats table.

Further, we don't have to make our own potentially confusing or non-sensical decision about what kinds of methods we will build to help our classes communicate with our database. Just like the save() method we previewed above, we will learn to build a series of common, conventional methods that our programs can rely on again and again to communicate with our database.

Top comments (0)