Object Relations in Python
Understanding object relations in data-based applications is essential. Object relations underscore how objects interact with each other. The most fundamental relationships are the one-to-many relationship and the many-to-many relationship. Object relations are achieved in Python via classes and object-oriented programming. Object Relational Mapping (ORM) is helpful in order ot use Python objects to interact with databases.
Get Nili (Scharf) Ambinder’s stories in your inbox
Join Medium for free to get updates from this writer.
In Python, object relations are demonstrated through classes. In a one-to-many relationship, for example, a single Author who writes many Books, the one-to-many relationship appears as follows:
class Author:
def __init__(self, name):
self.name = name
self.books = [] # initializing a list of books, this is the one-to-many relationship
def write_book(self, title):
book = Book(self, title)
self.books.append(book)
return book
class Book:
def __init__(self, author, title):
self.author = author
self.title = title
# Example
author = Author("Jack")
author.write_book("Object Relations")
print("author.book[0].title") # Output: Object Relations An example of a many-to-many relationship would be many authors who write many magazines:
class Magazine:
def __init__(self, name):
self.name = name
self.articles = []
def add_article(self, article):
self.articles.append(article)
class Article:
def __init__(self, author, magazine, title):
self.author = author
self.magazine = magazine
self.title = title
magazine.add_article(self)
# Example
author = Author("Jack")
magazine = Magazine("Techy")
author.write_article("Object Relations Explained")
Article(author, magazine, "Object Relations Explained")Using ORM helps us use Python objects in order to interact with databases in a very clear way.
Object relations are crucial to creating efficient applications. Python classes are the building blocks to better understand ORM’s and, in turn, improved interactions with databases in a productive and maintainable way.




