2026-09-01 12:30

Status:


DADSD - Module 2 - ORM Bridging the Gap Between the Real World and Relational Model

==Bridging the Gap Between the Real World and Relation Model

  • Introduction to Django:
    • Django is an open-source Python web framework that follows the MVC pattern

    • It is more expansive than another framework like flask, and is used to build back-end applications quickly and efficiently

    • It has a Rapid development and code reusability

    • For more see the IBM - Developing AI Applications with Python & Flask playlist

    • Users can use Django for really any web application that they would like:

      • Content Management System (CMS)
      • Social Media Platforms
      • Business Apps
      • New Websites
    • It is generally described as batteries included because of how comprehensive and extensive the framework is

    • It provides a wide variety of different features and functionalities out of the box

    • Object Relational Mapping (ORM) Layer which defines data models using python classes, which makes it easier to work with databases and perform CRUD operations

    • Template there is also a built-in template engine that allows for people to separate business logic from the presentation logic of the application, similar to something like flask

    • Administration basically an automatically generated admin interface based on the given models in your applications

    • It gives user-friendly methods of setting up admin content, and is also very customizable towards anything you would want to do

    • Security Django provides a good bit of website security with built in features like anti-cross site scripting (XSS), cross-site request forgery (CSRF), & SQL injection

    • It also has things like password hashing an session management as well

    • Authentication and Authorization- is also provided by the Django framework, with build in mechanisms for Managing user accounts, login and password management, and controls to define user permissions and access restrictions

    • Modules- Django, like node or flask and what not, also has different modules that are used to basically expand your code and give it more functionality, allowing you to download someone else’s boilerplate code and implement it in your own application

    • Shared Nothing Architecture- basically, Django operates on this notion that each web server instance basically works without depending on the others, making them basically stateless, or independent rather

    • This means that each web server instance handles request and response autonmously without relying on state resources or server side state

    • This makes it very easy to scale with Django because it allows managing user sessions letting you add more instances of your application without the excess clutter that comes along with state

    • Tests Django is good with testing as well, and includes a bunch of the standard tests you would expect like:

      • Unit
      • Standard
      • Functional
      • Test-Runner (which lets you run tests quickly and is basically a tool for running and writing tests)
    • Platform independence because the framework is basically written in python, which is a virtual machine running instance as an interpreted language, it basically allows for you to be able to run the code anywhere that supports python, which is basically everywhere

    • This means that you can also run your application on the cloud if you would generally want to, which is nice

    • There is also a LARGE community for the Django community and the python community in general. Django is also open-source which makes it nice since anyone can generally work on it

    • For example, Spotify, Instagram, and YouTube, all either started, are made in, or have used Django before

  • Object-Oriented Analysis and Design:
    • OOAD (Object-Oriented Analysis and Design)- is a system of design for a given application whenever an architecture will use Object-Oriented Programming Principles for it’s implementation
    • OOP basically objects and class programming. You have a base class blueprint that defines things like attributes and behavior/methods, and then you can create instances of that class which can assign and hold different values and use the defined methods
    • You are in some languages also able to dynamically change the number of attributes or add in different attributes to already created instances as well (generally not in the good languages tho ngl)
    • Therefore, you use OOAD for a system that can be broken down with different objects that would interact with one another
    • So you can have a bunch of different devs that can basically work on different aspects of the code at the same time and then just have them interplay with each other
    • More on this has been covered in courses like IBM Developing Back-End Applications with Node & IBM - Developing Front-End Apps with React
    • Pasted image 20260901134724.png
    • A class diagram like the one above can be used to showcase the way that classes might interact with in a given system, as well as some of their general methods and functions as well
    • This allows for you to communicate a OOAD system structure easily, showcasing relation and structure
  • Reading: ORM Tools:
    • ORM is basically a way to connect a database to an actual live back-end application

    • This way you can do things like use a programming language object and concept in order to do things like query and update a database

    • Letting you not have to worry about writing really complex and annoying SQL queries

    • Python

      • Django is a Python web framework with a built-in ORM that provides a high-level Application Programming Interface (API) for interacting with databases. Django offers features like model definition, query construction, database migrations, and automatic query optimization.

      • SQLAlchemy is a popular and comprehensive ORM library in Python, providing a flexible and expressive API for working with databases. SQLAlchemy offers high-level and low-level ORM approaches, allowing developers to choose the level of abstraction needed.

      • web2py is an open-source, full-stack web framework written in Python that aims to simplify web application development by providing an all-in-one solution that includes a web server, a database abstraction layer, and a web-based development environment.

    • Java

      • Hibernate is widely used for Java applications as it offers a powerful and feature-rich API for mapping Java objects to relational databases. Hibernate supports various database systems and provides advanced features like lazy loading, caching, and transaction management.
      • EclipseLink is another popular tool for Java. It’s an open-source framework that offers extensive support for mapping Java to relational databases. EclipseLink supports features like Java Persistence API (JPA), caching, advanced query capabilities, and integration with various application servers.
      • Apache OpenJPA is an open-source implementation of the JPA specification. It facilitates mapping Java classes to relational database tables and provides transparent persistence of Java objects.
    • .NET

      • Entity Framework is Microsoft’s ORM framework for .NET applications. It provides an easy-to-use API for mapping .NET objects to relational databases. Entity Framework supports different database providers, offers query capabilities, and includes features like code-first and database-first approaches for model creation.
      • Dapper is a micro-ORM for .NET that focuses on performance and simplicity. It provides a lightweight and efficient API for querying databases. Dapper is suitable for scenarios where direct control over SQL queries and execution is desired.
      • NHibernate is a widely used ORM tool for the .NET platform. It’s inspired by the Hibernate ORM tool for Java. NHibernate bridges object-oriented programming in .NET and relational databases, allowing developers to interact with databases using . NET objects.
    • Ruby

      • ActiveRecord is the default ORM in Ruby on Rails, a popular web framework in Ruby. It offers a convention-over-configuration approach, making mapping Ruby objects to database tables easy. ActiveRecord provides features like model associations, query generation, and database migrations.
      • Sequel is a flexible and feature-rich ORM tool for Ruby that emphasizes simplicity and a SQL-centric approach. Sequel supports various database systems, offers advanced query capabilities, and provides plugins for additional functionality.
      • DataMapper focuses on simplicity, flexibility, and ease of use. It aims to provide a clean and intuitive API for working with databases in Ruby applications. DataMappr features include flexible mapping, data abstraction, querying, and repository pattern.
    • PHP

      • Propel is a high-performance ORM tool for PHP that focuses on code generation and simplicity. It provides a code-first approach, where PHP classes and objects define the database schema. Propel generates efficient SQL queries and offers features like lazy loading, eager loading, and caching.
      • CakePHP includes a built-in ORM component that provides a powerful and intuitive API for working with databases, offering features like database abstraction, query building, and association management.
      • Eloquent is the default ORM provided by the Laravel framework, a popular PHP framework. It offers a straightforward and expressive syntax for defining database models and relationships. Eloquent simplifies database operations, including querying, data retrieval, and database migrations, and supports different database engines.
  • Object-Relational Mapping (ORM):
    • Pasted image 20260901140506.png
    • Using SQL in Applications- generally, whenever you are building any form of application, you would need to use some kind of SQL integration with a programming language using something like an API
    • This would then allow you to basically integrate SQL statements into your application code, letting you programmically run them and access your database
    • The Cursor Objects in the image above are basically special objects that are using for iterating over different rows in a given database
    • Pasted image 20260901140552.png
    • The above is a sample database example that uses the whole entity matching thing to conjoin the tables based on that whole PRIMARY Key stuff and what not, this time being the ID
    • Pasted image 20260901140635.png
    • This is then an execution of connecting over to the Database example and executing code on it. You would first use a database import like sqlite3 in order to connect yourself over to the database
    • Then you would use cursor to create objects that are representative of the database object that you just accessed via sqlite3
    • At which point you then write the SQL statement, and then you need to insert that statement inside of the middle man cursor object so it exists between the programming language and the database
    • Lastly, you can then basically execute the statement and the data you then would want is stored inside of the cursor object
    • Pasted image 20260901140939.png
    • This is basically just an example of OOP with two different classes and the way in which they would be able to connect to one another, and I would assume then that this is going to become representative of the database objects that exist inside of the ORM
    • I mean its just classes, its pretty clear to know how that works
    • Pasted image 20260901141055.png
    • Right, so in the code above you basically do the same thing where you have the data you fetch from the database using sqlite3 and then you use the cursor object and function to be able to write to and execute SQL queries on the database
    • The new addition however, is from then that database that you have, you use it in order to create a new Learner class, which you then populate with the data you got from the database
    • This then lets you store the data how you want to within of the class attributes, and then you can have these preventative object instance represent a row in the database
    • This then lets you append and run methods on these Learner objects, which let you do things with the, like neatly print it out for example
    • Differences between OOP and SQL
      • OOP models entities using classes, objects, and attributes, and using things like inheritance, association, and aggregation
      • SQL models entities using tables, rows, and columns, this however using things like JOIN and FOREIGN KEY
    • Pasted image 20260901144621.png
    • Basically, the people were really tired of using SQL and Classes for both things, and so they invented something called ORM (Object Relational Mapping) which allowed them to sort of using OOP to access database languages
    • It’s really kind of this middleman that you can use to do shit with relational databases
    • Pasted image 20260901144636.png
    • The above code on the right is the standard thing that you would use in order to connect to a database, and it shows the whole steps defined above
    • Then, on the right, is code that basically allows you to just import a given library which then just lets you do Course.Objects.get(name='Introduction to Python).learners.all(), which in general is a select statement that gives you information
    • Generally, I would prefer the more drawn out code than a bunch of class methods I would not be privy to, but whatever man anything to do it in one line of code I guess
    • Popular ORM libraries include Django & SQLAlchemy (Python), Hibernate, OpenJPA (Java), Sequelize, TypeORM (JavaScript)
    • Pros and Cons of ORM
      • You generally just need to define objects that define the database, which means no SQL and no Database libraries and such
      • You can also use databases without actually having to write any SQL queries as they all exist under the hood for you
      • You can also reuse the ORM for multiple different database systems without worrying about interference
      • SQL and OOP are still two different models, and ORM is just a middleman, which means that ORM might fail in doing exactly what you want in the process of translation
      • It moves data access complexity to the application code as well
      • It is also DIFFICULT ASF to debug because it abstracts all of the implementation details from you
  • Django Model:
    • Pasted image 20260901145358.png

    • The above is how the Django ORM can basically simplify a database query

    • Pasted image 20260901145444.png

    • Django models basically, each model or class you create is essentially an entire SQL table, and then each of the actual class objects or instances of it seems to be a table row that is represented

    • Each field inside of that given instance is then the column or attribute of the table

    • Generally, Django is able to automatically generate a table and schema once a class is generated

    • Pasted image 20260901145609.png

    • You can basically get into the nitty gritty of your column creation using the models field which lets you specify the other data params like you would inside of a CREATE TABLE SQL command

    • This way, you can create a new column in your database by having it exist as a field in your class, and then give it some preset value using the models class. Doing so, you can do things like set the datatype, or restrictions or other such things

    • Pasted image 20260901151223.png

    • Relationships

      • Pasted image 20260901150259.png
      • One-to-One- A relational model where logically you can only have something be either one thing or the other.
      • So if you have an instructor and a user, like in the above example, the one instructor can only have basic information stored in ONE user class, and one user can only have ONE role, either instructor or learner
      • This basically creates a relationship where one of the items is related to only one other item in the two separate tables
      • Django also then creates a foreign key pointing to user in the above code example so that way they can reference each other using that OneToOneField method call
      • Pasted image 20260901150541.png
      • Many-to-One basically, you may have one instance inside of a table that can then relate or include a number of many different items in a second table
      • In the above hand code, you have a given class of project and course, and in one table, an instance of course might reference many different projects in another table
      • While then something like multiple projects might be tied to a single course, hence the many to one relationship
      • The main thing that makes it different from the above example is that the foreign key might be the same for some of the project instances
      • Pasted image 20260901150751.png
      • Pasted image 20260901150829.png
      • Many-to-Many this is when you have something where one object might have many related objects in one table, and vise versa
      • So in something like a course and learner scenario, one course might have a bunch of learners, but a given learner might also have a bunch of different courses
      • This way you use the ManyToManyField to one of the models which would then tie up what it needs to tie up on both of the tables, and should go over to the class that is more likely to be edited more often
      • You can then also have this intermediary class that basically lets you keep track of who is connected to what, this generally isn’t like a traditional table as it seems, but is very useful for keeping good track of which user goes where in that many-to-many relation
    • Pasted image 20260901150955.png

    • Since each of these are technically a python class, this means that they can also inherit things from other python classes, which can be used in tandem to the ORM

    • This way you can do things like bookkeeping or going more into depth on a common object with a bunch of different and branching sub objects or something like that

  • Django Models CRUD:
    • Pasted image 20260901200707.png
    • CRUD (Create Read Update Delete)- and Django allows you a comprehensive list of models that let you update and perform these operations without writing any actual SQL queries
    • Pasted image 20260901200734.png
    • If you want to create and save a model instance, what you do is you create one with the given class definition, and then include the attributes you want it to have
    • To then basically save this to a database or something of the sort, you implemented the inherited save() method on the object, which then writes and updates that object to the database
    • If you have something like a reference to another table or database via something like a FOREIGN KEY, then you can also do so as in the code example shown above
    • Pasted image 20260901200941.png
    • Pasted image 20260901201309.png
    • The above is basically the equivalent of getting all given objects inside of a data table, and the thing that you would call it on, or the data object that is representative of the whole table, is what well, represents the whole table
    • By default the name of the model manage is objects and you can only access it using the model class, not the model instance itself, so this way an instance (which is representative of a row in the database) is not called and the class definition (representative of the table itself), is
    • Pasted image 20260901201513.png
    • To then basically use the WHERE clause, you can use the .filter() function, which takes in basically the exact same things that the WHERE clause does, you can also have multiple checks for different attributes as just other parameters passed into the function
    • This filter command can also then be chained onto itself, and can too be used with the exclude() command, and this is similar to the concept of a bunch of AND statements inside of an SQL query
    • Pasted image 20260901201714.png
    • If there is only a single object that would match your given query, then you can use the get() method, which would then take in the exact attribute that is only singular to that instance
    • This then is basically a nice shorthand and faster way of accessing something that you know there will only be one of
    • Pasted image 20260901201930.png
    • There is also a way to get objects in related fields as well, basically foreign keys that are pointing to other tables and could be joined to obtain new data from an SQL perspective, or from the OOP perspective a relation to another model via an instance’s field value
    • Django basically handles the JOIN SQL command automatically, and the syntax for it would be a double underscore as shown above
    • You can also update database data in multiple ways, with the most simple one being to update the actual fields of the object instance, and then basically run a save() method on such a thing
    • You call delete() on a on object to delete instance it from the database

==Summary

  • The Object-Oriented Programming (OOP) and SQL paradigm model data differently.
  • Object Relational Mapping, or ORM bridges the gap between OOP and SQL.
  • ORM libraries or tools can map and transfer data stored in a relational database as rows into objects or objects into rows.
  • ORM allows developers to use OOP to query and manipulate data because it transfers objects into rows and rows into objects.
  • Django ORM is a Python ORM component that belongs to the Django web application framework.
  • Django ORM can help speed up database development because you define maps to a database table for each Django model.
  • Each Django field maps to a column type.
  • Django automatically creates tables once models and fields are defined.
  • Django APIs can perform Create, Read, Update, and Delete (CRUD) operations on database objects.
  • In a Django model, you create an object and call the model’s save method to insert it into the database as a record.
  • You must construct a QuerySet using a Manager on your model class to read objects using Django Model API.
  • There are several ways to update database records in Django by updating objects.
  • To delete records in a database, you call Django ORM’s Delete method on a model object or query set.

==Cheat Sheet

Package/MethodDescriptionCode Example
django.db.models.ModelDefine a model.from django.db import models

class MyModel(models.Model):

    field1 = models.CharField(max_length=100)

    field2 = models.IntegerField()
makemigrations/migrateCreate database tables based on models.python manage.py makemigrations

python manage.py migrate
all()Retrieves all instances of the ‘MyModel’ model from the database.MyModel.objects.all()
filter()Filter objects using conditions.MyModel.objects.filter(field1=“value”)

MyModel.objects.filter(field2__gt=5)
get()Retrieves a single instance of the ‘MyModel’ model from the database where the value of ‘field1’ is “value”.MyModel.objects.get(field1=“value”)
obj = MyModel(field1=“value”, field2=5)

obj.save()
Creates a new instance of the ‘MyModel’ model with the values “value” for ‘field1’ and 5 for ‘field2’, and then saves the instance to the database.obj = MyModel(field1=“value”, field2=5)

obj.save()
obj.field1 = “new value”

obj.save()
Updates the value of ‘field1’ for the ‘obj’ instance to “new value” and saves the changes to the database.obj.field1 = “new value”

obj.save()
delete()Deletes an object.obj.delete()
obj.related_modelRetrieves the related model associated with the ‘obj’ instance. Access related objects (Foreign Key or OneToOneField)obj.related_model
obj.model_set.all()Fetches all related objects associated with the ‘obj’ instance. Access related objects in reverse (ForeignKey)obj.model_set.all()
fieldPerforms a filtering operation on the ‘MyModel’ model instances based on a related model’s field value.MyModel.objects.filter(related_model__field=“value”)
exactRetrieves instances of the ‘MyModel’ model from the database where the value of the ‘field’ attribute is exactly equal to “value”.MyModel.objects.filter(field__exact=“value”)
iexactThe iexact lookup is case-insensitive, meaning it will match values regardless of whether they are uppercase or lowercase and provide a case-insensitive match.MyModel.objects.filter(field__iexact=“value”)
containsChecks if the value is a substring within the field.MyModel.objects.filter(field__contains=“value”)
startswithDetermines whether a string begins with the characters of a specified string.MyModel.objects.filter(field__startswith=“value”)
endswithDetermines whether a string ends with the specified suffix.MyModel.objects.filter(field__endswith=“value”)
inChecks if the value of the field is present in the given list of values.MyModel.objects.filter(field__in=[“value1”, “value2”])
gtChecks if the value of ‘field’ is numerically greater than 5.MyModel.objects.filter(field__gt=5)
ltChecks if the value of ‘field’ is numerically less than 10.MyModel.objects.filter(field__lt=10)

References