SlideShare a Scribd company logo
DJANGO APPS AND ORM
PRODUCT VALLEY MEETUP GROUP BANGALORE (A PRODEERS CHAPTER)
- BY UDIT GANGWANI
ABOUT ME
I WEAR MULTIPLE HATS
SOFTWARE DEVELOPER
PRODUCT MANAGER
ENTREPRENEUR
I LOVE TO TRAVEL
MY FRIENDS CALL ME PIZZA MANIAC
WHAT WILL WE LEARN TODAY
INTRODUCTION TO DJANGO
HOW TO GET STARTED WITH DJANGO
COMPONENTS OF DJANGO FRAMEWORK
DJANGO MODELS, MODEL MANAGERS AND QUERY SETS
HOW DO DJANGO MODELS WORK
WHAT IS DJANGO ?
Django is a high-level Python Web framework that encourages rapid
development and clean, pragmatic design. Built by experienced developers, it
takes care of much of the hassle of Web development, so you can focus on
writing your app without needing to reinvent the wheel.
-- https://www.djangoproject.com/
WHY DJANGO ?
• Incredible programming language (Python)
• Perfect ORM for handling database
• Offers great control (Explicit is better than implicit)
• Django Admin GUI
• Simple and smaller footprint to get started
• Very big & active community
• Lots of Django packages for almost every functionality
• Support for large variants of Databases
• Django REST Framework
MTV ARCHITECTURE
Django follows MTV architecture:
M – Model
• app/models.py
V – View
• app/views.py
T – Templates
• app/templates/*.html
It is analogous to MVC architecture.
View in MVC corresponds to
Template in MTV
Controller in MVC corresponds to
View in MTV
POPULAR SITES BUILT WITH DJANGO
• Pinterest
• Instagram
• Discus
• Spotify
• Washington Post
• Firefox
• NASA
• BitBucket
• Prezi
• EventBrite
DJANGO SETUP AND A DEMO
ENVIRONMENT SETUP
• Standard Environment
• Common environment and set of packages for each project on your system
• Virtual Environment
• Isolated environment for each Django project
• No limits on the number of environments
• Can have different python version for each project
• Using virtualenv or pyenv
STEPS TO SETUP VIRTUAL ENVIRONMENT
• pip install virtualenv
• virtualenv .app
• source appbinactivate
GETTING STARTED WITH DJANGO
• Install Django using pip
• Create a project using django-admin
• Create your database
• Configure DB settings in settings.py
• Define your models
• Add external modules
• Write your Templates
• Define your Urls
• Write your Views and bind them to Urls
• Test application
• Deploy application using NginX or Apache
DJANGO PROJECT STRUCTURE
• Each Django app is a Python Package
• Each app contains one or more Python
modules (files of python code)
• To form a package every app directory
must contain an __init__.py file
BLOG APPLICATION DEMO
DJANGO COMPONENTS
URL’S DISPATCHER/ROUTING
• Django determines the root URLconf module to use
• Django loads the Python module and looks for the variable urlpatterns
• Django runs through each pattern and stops at the one which matches
• Once the regex matches, Django calls the given View
VIEWS
• A Django view is a callable which takes a request and returns a response
MODELS & MODEL FIELDS
• Each model maps to a single database table.
• Each model is a Python class that subclasses django.db.models.Model
• Each attribute of the model represents a database field
TEMPLATES
• A template contains the static parts of the desired HTML output as well as
some special syntax describing how dynamic content will be inserted
MIDDLEWARES
• Middleware is a framework of hooks into Django’s request/response
processing. It’s a light, low-level “plugin” system for globally altering
Django’s input or output.
DJANGO MODELS
MIGRATIONS
• Migrations are Django’s way of propagating changes you make to your
models (adding a field, deleting a model, etc.) into your database schema.
• They’re designed to be mostly automatic
Thereareseveralcommandswhichyouwilluse tointeractwithmigrations:
•migrate,whichisresponsibleforapplyingmigrations,aswellas unapplyingandlistingtheirstatus.
•makemigrations,whichisresponsibleforcreatingnewmigrationsbasedonthechangesyouhavemadetoyourmodels.
•sqlmigrate,whichdisplaystheSQLstatementsforamigration.
•showmigrations,whichlistsaproject’smigrations.
MODEL RELATIONSHIPS
Many to One Relationships Many to Many Relationships
One to One Relationships
MODEL QUERIES
• Creating Objects
• Retrieving Objects
• Create query set objects using your model manager. A query set represents the
collection of objects from database
• Query sets are lazy
• Retrieving specific objects using filters
MODEL QUERIES ON RELATED OBJECTS
One to Many Field
One to One Many Reverse lookup
Many to Many Field
One to One Field
MANAGERS
• A Manager is the interface through which database query operations are
provided to Django models. At least one Manager exists for every model in a
Django application.
• Adding extra Manager methods is the preferred way to add “table-level”
functionality to your models. (For “row-level” functionality – i.e., functions
that act on a single instance of a model object – use Model methods, not
custom Manager methods.)
MANAGERS EXAMPLE
QUERY SETS
• Internally, a QuerySet can be constructed, filtered, sliced, and generally
passed around without actually hitting the database. No database activity
actually occurs until you do something to evaluate the queryset.
• Important methods that return new Query set
• filter(), exclude(), annotate(), order_by(), reverse(), distinct(), values(), all()
• Important methods that do not return Query set
• get(), create(), update(), aggregate(), iterator(), count()
Q OBJECTS
• A Q object (django.db.models.Q) is an object used to encapsulate a
collection of keyword arguments. It is used to execute more complex queries
(for example, queries with OR statements)
AGGREGATION
Aggregation for entire table
Aggregation for each item
in table
HOW DO DJANGO MODELS WORK ?
HOW DO MODELS WORK - METACLASSES
Lets understand what goes on from the time a model is imported until an
instance is created by the user.
Lets look at an example model
HOW DO MODELS WORK - METACLASSES
So ModelBase.__new__ is called to create this new Example class. It is important to realise that we are
creating the class object here, not an instance of it
The Model class (see base.py) has a __metaclass__ attribute that defines ModelBase (also in base.py) as
the class to use for creating new classes.
The __new__ method is required to return a class object that can then be instantiated (by calling
Example() in our case).
A new class object with the Example name is created in the right module namespace. A _meta attribute
is added to hold all of the field validation, retrieval and saving machinery
HOW DO MODELS WORK - METACLASSES
Each attribute is then added to the new class object. Putting this in the context of our example, the
static and __unicode__ attributes would be added normally to the class as a string object and unbound
method, respectively.
In case of Field, it does not add the new attribute to the class we are creating (Example). Instead it adds
itself to the Example._meta class, ending up in the Example._meta.fields list
The ModelBase._prepare method is called. This sets up a few model methods that might be required
depending on other options you have selected and adds a primary key field if one has not been explicitly
declared.
The registration is done right at the end of the ModelBase.__new__ method. The register_models()
function in loaders.py
REFERENCES
• Django Orm at Django under the hood: https://www.youtube.com/watch?v=CGF-0csOjPw
• Django Topics: https://docs.djangoproject.com/en/1.9/topics/
• What is a MetaClass in Python: http://stackoverflow.com/questions/100003/what-is-a-
metaclass-in-python
• How do Django Models work:
• http://stackoverflow.com/questions/12006267/how-do-django-models-work
• https://code.djangoproject.com/wiki/DevModelCreation
• Django Cookbook: https://code.djangoproject.com/wiki/CookBook
• Python3 Cookbook: http://python3-
cookbook.readthedocs.io/zh_CN/latest/c09/p18_define_classes_programmatically.html
REFERENCES
• Try Django Blog Project:
• https://github.com/codingforentrepreneurs/try-django-19
• https://www.codingforentrepreneurs.com/projects/try-django-19/
• Django Models and Migrations:
• http://www.webforefront.com/django/setupdjangomodels.html
• Making Django Queries :
• https://docs.djangoproject.com/en/1.9/topics/db/queries/
• Understanding Django Model Managers and QuerySets:
• https://docs.djangoproject.com/en/1.9/ref/models/querysets/
• https://docs.djangoproject.com/en/1.9/topics/db/managers/
THANK YOU

More Related Content

PPTX
templates in Django material : Training available at Baabtra
baabtra.com - No. 1 supplier of quality freshers
 
KEY
Jumpstart Your Development with ZopeSkel
Cristopher Ewing
 
PDF
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
WordCamp Sydney
 
PPTX
An Overview of Models in Django
Michael Auritt
 
PPTX
Django: Advanced Models
Ying-An Lai
 
PPTX
Django Girls Tutorial
Kishimi Ibrahim Ishaq
 
PDF
Working with the django admin
flywindy
 
PDF
Page Object Model and Implementation in Selenium
Zoe Gilbert
 
templates in Django material : Training available at Baabtra
baabtra.com - No. 1 supplier of quality freshers
 
Jumpstart Your Development with ZopeSkel
Cristopher Ewing
 
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
WordCamp Sydney
 
An Overview of Models in Django
Michael Auritt
 
Django: Advanced Models
Ying-An Lai
 
Django Girls Tutorial
Kishimi Ibrahim Ishaq
 
Working with the django admin
flywindy
 
Page Object Model and Implementation in Selenium
Zoe Gilbert
 

What's hot (15)

PDF
Django
Amanpreet Singh
 
PPTX
Two scoops of django Introduction
flywindy
 
PDF
Django Introduction & Tutorial
之宇 趙
 
PPTX
Effiziente persistierung
Thorben Janssen
 
PPTX
Integration patterns in AEM 6
Yuval Ararat
 
PDF
slingmodels
Ankur Chauhan
 
PPTX
Super keyword in java
Hitesh Kumar
 
PPT
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Thorben Janssen
 
PPTX
Using velocity Templates(An overview)
Nwabueze Obioma
 
PDF
Django: Beyond Basics
arunvr
 
PDF
Using java beans(ii)
Ximentita Hernandez
 
PDF
Java ap is you should know
Hendrik Ebbers
 
PDF
Drupal8 for Symfony Developers (PHP Day Verona 2017)
Antonio Peric-Mazar
 
PDF
Core data WIPJam workshop @ MWC'14
Diego Freniche Brito
 
PPT
Coding with style: The Scalastyle style checker
Matthew Farwell
 
Two scoops of django Introduction
flywindy
 
Django Introduction & Tutorial
之宇 趙
 
Effiziente persistierung
Thorben Janssen
 
Integration patterns in AEM 6
Yuval Ararat
 
slingmodels
Ankur Chauhan
 
Super keyword in java
Hitesh Kumar
 
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Thorben Janssen
 
Using velocity Templates(An overview)
Nwabueze Obioma
 
Django: Beyond Basics
arunvr
 
Using java beans(ii)
Ximentita Hernandez
 
Java ap is you should know
Hendrik Ebbers
 
Drupal8 for Symfony Developers (PHP Day Verona 2017)
Antonio Peric-Mazar
 
Core data WIPJam workshop @ MWC'14
Diego Freniche Brito
 
Coding with style: The Scalastyle style checker
Matthew Farwell
 
Ad

Viewers also liked (12)

PDF
InterConnect2016: WebApp Architectures with Java and Node.js
Chris Bailey
 
PDF
Enterprise makeover. Be a good web citizen, deliver continuously and change y...
Mateusz Kwasniewski
 
PPTX
How NOT to write in Node.js
Piotr Pelczar
 
PDF
(node.js) Web Development - prościej
Mateusz Kwasniewski
 
PPTX
Managing and Versioning Machine Learning Models in Python
Simon Frid
 
PDF
How to Write a Popular Python Library by Accident
Daniel Greenfeld
 
PPTX
Web backends development using Python
Ayun Park
 
PDF
State of Tech in Texas
Experts Exchange
 
PDF
The Django Web Application Framework
Simon Willison
 
PDF
Web Development with Python and Django
Michael Pirnat
 
PPTX
Connecting With the Disconnected
Chris Wejr
 
PPTX
Can We Assess Creativity?
John Spencer
 
InterConnect2016: WebApp Architectures with Java and Node.js
Chris Bailey
 
Enterprise makeover. Be a good web citizen, deliver continuously and change y...
Mateusz Kwasniewski
 
How NOT to write in Node.js
Piotr Pelczar
 
(node.js) Web Development - prościej
Mateusz Kwasniewski
 
Managing and Versioning Machine Learning Models in Python
Simon Frid
 
How to Write a Popular Python Library by Accident
Daniel Greenfeld
 
Web backends development using Python
Ayun Park
 
State of Tech in Texas
Experts Exchange
 
The Django Web Application Framework
Simon Willison
 
Web Development with Python and Django
Michael Pirnat
 
Connecting With the Disconnected
Chris Wejr
 
Can We Assess Creativity?
John Spencer
 
Ad

Similar to Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com] (20)

PPTX
1-_Introduction_To_Django_Model_and_Database (1).pptx
TamilGamers4
 
PPTX
Basic Python Django
Kaleem Ullah Mangrio
 
PPTX
Web development with django - Basics Presentation
Shrinath Shenoy
 
PPTX
Introduction to DJANGO, a creative framework
bunnybro2953
 
PPTX
Introduction to Django
Ahmed Salama
 
PDF
Django Documentation
Ying wei (Joe) Chou
 
PDF
django
webuploader
 
PDF
Introduction to Python and Django
solutionstreet
 
PDF
Django
Narcisse Siewe
 
KEY
Introduction to Django
James Casey
 
PDF
Rapid web application development using django - Part (1)
Nishant Soni
 
PPTX
Unleash-the-power-of-Django.pptx
ShivamSv1
 
PDF
Django
sisibeibei
 
PDF
Django Workflow and Architecture
Andolasoft Inc
 
PDF
Python Metaclass and How Django uses them: Foss 2010
Agiliq Info Solutions India Pvt Ltd
 
PDF
Doing magic with python metaclasses
Agiliq Solutions
 
PPTX
Django Framework Interview Guide - Part 1
To Sum It Up
 
PPTX
Django Framework Overview forNon-Python Developers
Rosario Renga
 
PDF
Django introduction @ UGent
kevinvw
 
1-_Introduction_To_Django_Model_and_Database (1).pptx
TamilGamers4
 
Basic Python Django
Kaleem Ullah Mangrio
 
Web development with django - Basics Presentation
Shrinath Shenoy
 
Introduction to DJANGO, a creative framework
bunnybro2953
 
Introduction to Django
Ahmed Salama
 
Django Documentation
Ying wei (Joe) Chou
 
django
webuploader
 
Introduction to Python and Django
solutionstreet
 
Introduction to Django
James Casey
 
Rapid web application development using django - Part (1)
Nishant Soni
 
Unleash-the-power-of-Django.pptx
ShivamSv1
 
Django
sisibeibei
 
Django Workflow and Architecture
Andolasoft Inc
 
Python Metaclass and How Django uses them: Foss 2010
Agiliq Info Solutions India Pvt Ltd
 
Doing magic with python metaclasses
Agiliq Solutions
 
Django Framework Interview Guide - Part 1
To Sum It Up
 
Django Framework Overview forNon-Python Developers
Rosario Renga
 
Django introduction @ UGent
kevinvw
 

Recently uploaded (20)

PDF
Doc9.....................................
SofiaCollazos
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PDF
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PPTX
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
Doc9.....................................
SofiaCollazos
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
OFFOFFBOX™ – A New Era for African Film | Startup Presentation
ambaicciwalkerbrian
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
IT Runs Better with ThousandEyes AI-driven Assurance
ThousandEyes
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 

Django apps and ORM Beyond the basics [Meetup hosted by Prodeers.com]

  • 1. DJANGO APPS AND ORM PRODUCT VALLEY MEETUP GROUP BANGALORE (A PRODEERS CHAPTER) - BY UDIT GANGWANI
  • 2. ABOUT ME I WEAR MULTIPLE HATS SOFTWARE DEVELOPER PRODUCT MANAGER ENTREPRENEUR I LOVE TO TRAVEL MY FRIENDS CALL ME PIZZA MANIAC
  • 3. WHAT WILL WE LEARN TODAY INTRODUCTION TO DJANGO HOW TO GET STARTED WITH DJANGO COMPONENTS OF DJANGO FRAMEWORK DJANGO MODELS, MODEL MANAGERS AND QUERY SETS HOW DO DJANGO MODELS WORK
  • 4. WHAT IS DJANGO ? Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. -- https://www.djangoproject.com/
  • 5. WHY DJANGO ? • Incredible programming language (Python) • Perfect ORM for handling database • Offers great control (Explicit is better than implicit) • Django Admin GUI • Simple and smaller footprint to get started • Very big & active community • Lots of Django packages for almost every functionality • Support for large variants of Databases • Django REST Framework
  • 6. MTV ARCHITECTURE Django follows MTV architecture: M – Model • app/models.py V – View • app/views.py T – Templates • app/templates/*.html It is analogous to MVC architecture. View in MVC corresponds to Template in MTV Controller in MVC corresponds to View in MTV
  • 7. POPULAR SITES BUILT WITH DJANGO • Pinterest • Instagram • Discus • Spotify • Washington Post • Firefox • NASA • BitBucket • Prezi • EventBrite
  • 9. ENVIRONMENT SETUP • Standard Environment • Common environment and set of packages for each project on your system • Virtual Environment • Isolated environment for each Django project • No limits on the number of environments • Can have different python version for each project • Using virtualenv or pyenv
  • 10. STEPS TO SETUP VIRTUAL ENVIRONMENT • pip install virtualenv • virtualenv .app • source appbinactivate
  • 11. GETTING STARTED WITH DJANGO • Install Django using pip • Create a project using django-admin • Create your database • Configure DB settings in settings.py • Define your models • Add external modules • Write your Templates • Define your Urls • Write your Views and bind them to Urls • Test application • Deploy application using NginX or Apache
  • 12. DJANGO PROJECT STRUCTURE • Each Django app is a Python Package • Each app contains one or more Python modules (files of python code) • To form a package every app directory must contain an __init__.py file
  • 15. URL’S DISPATCHER/ROUTING • Django determines the root URLconf module to use • Django loads the Python module and looks for the variable urlpatterns • Django runs through each pattern and stops at the one which matches • Once the regex matches, Django calls the given View
  • 16. VIEWS • A Django view is a callable which takes a request and returns a response
  • 17. MODELS & MODEL FIELDS • Each model maps to a single database table. • Each model is a Python class that subclasses django.db.models.Model • Each attribute of the model represents a database field
  • 18. TEMPLATES • A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted
  • 19. MIDDLEWARES • Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output.
  • 21. MIGRATIONS • Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. • They’re designed to be mostly automatic Thereareseveralcommandswhichyouwilluse tointeractwithmigrations: •migrate,whichisresponsibleforapplyingmigrations,aswellas unapplyingandlistingtheirstatus. •makemigrations,whichisresponsibleforcreatingnewmigrationsbasedonthechangesyouhavemadetoyourmodels. •sqlmigrate,whichdisplaystheSQLstatementsforamigration. •showmigrations,whichlistsaproject’smigrations.
  • 22. MODEL RELATIONSHIPS Many to One Relationships Many to Many Relationships One to One Relationships
  • 23. MODEL QUERIES • Creating Objects • Retrieving Objects • Create query set objects using your model manager. A query set represents the collection of objects from database • Query sets are lazy • Retrieving specific objects using filters
  • 24. MODEL QUERIES ON RELATED OBJECTS One to Many Field One to One Many Reverse lookup Many to Many Field One to One Field
  • 25. MANAGERS • A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application. • Adding extra Manager methods is the preferred way to add “table-level” functionality to your models. (For “row-level” functionality – i.e., functions that act on a single instance of a model object – use Model methods, not custom Manager methods.)
  • 27. QUERY SETS • Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database. No database activity actually occurs until you do something to evaluate the queryset. • Important methods that return new Query set • filter(), exclude(), annotate(), order_by(), reverse(), distinct(), values(), all() • Important methods that do not return Query set • get(), create(), update(), aggregate(), iterator(), count()
  • 28. Q OBJECTS • A Q object (django.db.models.Q) is an object used to encapsulate a collection of keyword arguments. It is used to execute more complex queries (for example, queries with OR statements)
  • 29. AGGREGATION Aggregation for entire table Aggregation for each item in table
  • 30. HOW DO DJANGO MODELS WORK ?
  • 31. HOW DO MODELS WORK - METACLASSES Lets understand what goes on from the time a model is imported until an instance is created by the user. Lets look at an example model
  • 32. HOW DO MODELS WORK - METACLASSES So ModelBase.__new__ is called to create this new Example class. It is important to realise that we are creating the class object here, not an instance of it The Model class (see base.py) has a __metaclass__ attribute that defines ModelBase (also in base.py) as the class to use for creating new classes. The __new__ method is required to return a class object that can then be instantiated (by calling Example() in our case). A new class object with the Example name is created in the right module namespace. A _meta attribute is added to hold all of the field validation, retrieval and saving machinery
  • 33. HOW DO MODELS WORK - METACLASSES Each attribute is then added to the new class object. Putting this in the context of our example, the static and __unicode__ attributes would be added normally to the class as a string object and unbound method, respectively. In case of Field, it does not add the new attribute to the class we are creating (Example). Instead it adds itself to the Example._meta class, ending up in the Example._meta.fields list The ModelBase._prepare method is called. This sets up a few model methods that might be required depending on other options you have selected and adds a primary key field if one has not been explicitly declared. The registration is done right at the end of the ModelBase.__new__ method. The register_models() function in loaders.py
  • 34. REFERENCES • Django Orm at Django under the hood: https://www.youtube.com/watch?v=CGF-0csOjPw • Django Topics: https://docs.djangoproject.com/en/1.9/topics/ • What is a MetaClass in Python: http://stackoverflow.com/questions/100003/what-is-a- metaclass-in-python • How do Django Models work: • http://stackoverflow.com/questions/12006267/how-do-django-models-work • https://code.djangoproject.com/wiki/DevModelCreation • Django Cookbook: https://code.djangoproject.com/wiki/CookBook • Python3 Cookbook: http://python3- cookbook.readthedocs.io/zh_CN/latest/c09/p18_define_classes_programmatically.html
  • 35. REFERENCES • Try Django Blog Project: • https://github.com/codingforentrepreneurs/try-django-19 • https://www.codingforentrepreneurs.com/projects/try-django-19/ • Django Models and Migrations: • http://www.webforefront.com/django/setupdjangomodels.html • Making Django Queries : • https://docs.djangoproject.com/en/1.9/topics/db/queries/ • Understanding Django Model Managers and QuerySets: • https://docs.djangoproject.com/en/1.9/ref/models/querysets/ • https://docs.djangoproject.com/en/1.9/topics/db/managers/