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
KEY
Jumpstart Your Development with ZopeSkel
PDF
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
PPTX
An Overview of Models in Django
PPTX
Django: Advanced Models
PPTX
Django Girls Tutorial
PDF
Working with the django admin
PDF
Page Object Model and Implementation in Selenium
templates in Django material : Training available at Baabtra
Jumpstart Your Development with ZopeSkel
Stop Hacking WordPress, Start Working with it - Charly Leetham - WordCamp Syd...
An Overview of Models in Django
Django: Advanced Models
Django Girls Tutorial
Working with the django admin
Page Object Model and Implementation in Selenium

What's hot (15)

PDF
PPTX
Two scoops of django Introduction
PDF
Django Introduction & Tutorial
PPTX
Effiziente persistierung
PPTX
Integration patterns in AEM 6
PDF
slingmodels
PPTX
Super keyword in java
PPT
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
PPTX
Using velocity Templates(An overview)
PDF
Django: Beyond Basics
PDF
Using java beans(ii)
PDF
Java ap is you should know
PDF
Drupal8 for Symfony Developers (PHP Day Verona 2017)
PDF
Core data WIPJam workshop @ MWC'14
PPT
Coding with style: The Scalastyle style checker
Two scoops of django Introduction
Django Introduction & Tutorial
Effiziente persistierung
Integration patterns in AEM 6
slingmodels
Super keyword in java
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Using velocity Templates(An overview)
Django: Beyond Basics
Using java beans(ii)
Java ap is you should know
Drupal8 for Symfony Developers (PHP Day Verona 2017)
Core data WIPJam workshop @ MWC'14
Coding with style: The Scalastyle style checker
Ad

Viewers also liked (12)

PDF
InterConnect2016: WebApp Architectures with Java and Node.js
PDF
Enterprise makeover. Be a good web citizen, deliver continuously and change y...
PPTX
How NOT to write in Node.js
PDF
(node.js) Web Development - prościej
PPTX
Managing and Versioning Machine Learning Models in Python
PDF
How to Write a Popular Python Library by Accident
PPTX
Web backends development using Python
PDF
State of Tech in Texas
PDF
The Django Web Application Framework
PDF
Web Development with Python and Django
PPTX
Connecting With the Disconnected
PPTX
Can We Assess Creativity?
InterConnect2016: WebApp Architectures with Java and Node.js
Enterprise makeover. Be a good web citizen, deliver continuously and change y...
How NOT to write in Node.js
(node.js) Web Development - prościej
Managing and Versioning Machine Learning Models in Python
How to Write a Popular Python Library by Accident
Web backends development using Python
State of Tech in Texas
The Django Web Application Framework
Web Development with Python and Django
Connecting With the Disconnected
Can We Assess Creativity?
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
PPTX
Basic Python Django
PPTX
Web development with django - Basics Presentation
PPTX
Introduction to DJANGO, a creative framework
PPTX
Introduction to Django
PDF
Django Documentation
PDF
django
PDF
Introduction to Python and Django
PDF
KEY
Introduction to Django
PDF
Rapid web application development using django - Part (1)
PPTX
Unleash-the-power-of-Django.pptx
PDF
Django
PDF
Django Workflow and Architecture
PDF
Python Metaclass and How Django uses them: Foss 2010
PDF
Doing magic with python metaclasses
PPTX
Django Framework Interview Guide - Part 1
PPTX
Django Framework Overview forNon-Python Developers
PDF
Django introduction @ UGent
1-_Introduction_To_Django_Model_and_Database (1).pptx
Basic Python Django
Web development with django - Basics Presentation
Introduction to DJANGO, a creative framework
Introduction to Django
Django Documentation
django
Introduction to Python and Django
Introduction to Django
Rapid web application development using django - Part (1)
Unleash-the-power-of-Django.pptx
Django
Django Workflow and Architecture
Python Metaclass and How Django uses them: Foss 2010
Doing magic with python metaclasses
Django Framework Interview Guide - Part 1
Django Framework Overview forNon-Python Developers
Django introduction @ UGent

Recently uploaded (20)

PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Approach and Philosophy of On baking technology
PPT
Teaching material agriculture food technology
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Machine learning based COVID-19 study performance prediction
PPTX
Big Data Technologies - Introduction.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Cloud computing and distributed systems.
PDF
Modernizing your data center with Dell and AMD
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
The Rise and Fall of 3GPP – Time for a Sabbatical?
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
NewMind AI Weekly Chronicles - August'25 Week I
Understanding_Digital_Forensics_Presentation.pptx
Electronic commerce courselecture one. Pdf
Unlocking AI with Model Context Protocol (MCP)
Approach and Philosophy of On baking technology
Teaching material agriculture food technology
Spectral efficient network and resource selection model in 5G networks
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
The AUB Centre for AI in Media Proposal.docx
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Machine learning based COVID-19 study performance prediction
Big Data Technologies - Introduction.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Cloud computing and distributed systems.
Modernizing your data center with Dell and AMD
Reach Out and Touch Someone: Haptics and Empathic Computing
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...

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/