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

What's hot

Django
DjangoDjango
Two scoops of django Introduction
Two scoops of django IntroductionTwo scoops of django Introduction
Two scoops of django Introduction
flywindy
 
Django Introduction & Tutorial
Django Introduction & TutorialDjango Introduction & Tutorial
Django Introduction & Tutorial
之宇 趙
 
Effiziente persistierung
Effiziente persistierungEffiziente persistierung
Effiziente persistierung
Thorben Janssen
 
Integration patterns in AEM 6
Integration patterns in AEM 6Integration patterns in AEM 6
Integration patterns in AEM 6
Yuval Ararat
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Performance Tuning with JPA 2.1 and Hibernate (Geecon Prague 2015)
Thorben Janssen
 
Using velocity Templates(An overview)
Using velocity Templates(An overview)Using velocity Templates(An overview)
Using velocity Templates(An overview)
Nwabueze Obioma
 
Django: Beyond Basics
Django: Beyond BasicsDjango: Beyond Basics
Django: Beyond Basicsarunvr
 
Java ap is you should know
Java ap is you should knowJava ap is you should know
Java ap is you should know
Hendrik Ebbers
 
Drupal8 for Symfony Developers (PHP Day Verona 2017)
Drupal8 for Symfony Developers (PHP Day Verona 2017)Drupal8 for Symfony Developers (PHP Day Verona 2017)
Drupal8 for Symfony Developers (PHP Day Verona 2017)
Antonio Peric-Mazar
 
Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14
Diego Freniche Brito
 
Coding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checkerCoding with style: The Scalastyle style checker
Coding with style: The Scalastyle style checker
Matthew Farwell
 

What's hot (15)

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

Viewers also liked

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

Viewers also liked (12)

InterConnect2016: WebApp Architectures with Java and Node.js
InterConnect2016: WebApp Architectures with Java and Node.jsInterConnect2016: WebApp Architectures with Java and Node.js
InterConnect2016: WebApp Architectures with Java and Node.js
 
Enterprise makeover. Be a good web citizen, deliver continuously and change y...
Enterprise makeover. Be a good web citizen, deliver continuously and change y...Enterprise makeover. Be a good web citizen, deliver continuously and change y...
Enterprise makeover. Be a good web citizen, deliver continuously and change y...
 
How NOT to write in Node.js
How NOT to write in Node.jsHow NOT to write in Node.js
How NOT to write in Node.js
 
(node.js) Web Development - prościej
(node.js) Web Development - prościej(node.js) Web Development - prościej
(node.js) Web Development - prościej
 
Managing and Versioning Machine Learning Models in Python
Managing and Versioning Machine Learning Models in PythonManaging and Versioning Machine Learning Models in Python
Managing and Versioning Machine Learning Models in Python
 
How to Write a Popular Python Library by Accident
How to Write a Popular Python Library by AccidentHow to Write a Popular Python Library by Accident
How to Write a Popular Python Library by Accident
 
Web backends development using Python
Web backends development using PythonWeb backends development using Python
Web backends development using Python
 
State of Tech in Texas
State of Tech in TexasState of Tech in Texas
State of Tech in Texas
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
 
Web Development with Python and Django
Web Development with Python and DjangoWeb Development with Python and Django
Web Development with Python and Django
 
Connecting With the Disconnected
Connecting With the DisconnectedConnecting With the Disconnected
Connecting With the Disconnected
 
Can We Assess Creativity?
Can We Assess Creativity?Can We Assess Creativity?
Can We Assess Creativity?
 

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

GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineYared Ayalew
 
Why Django for Web Development
Why Django for Web DevelopmentWhy Django for Web Development
Why Django for Web Development
Morteza Zohoori Shoar
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
Ksd Che
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
Wade Austin
 
Tango with django
Tango with djangoTango with django
Tango with django
Rajan Kumar Upadhyay
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to djangoIlian Iliev
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
Django interview Questions| Edureka
Django interview  Questions| EdurekaDjango interview  Questions| Edureka
Django interview Questions| Edureka
Edureka!
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAE
Winston Chen
 
Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)
Nishant Soni
 
django
djangodjango
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
Knoldus Inc.
 
Get things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplicationsGet things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplications
Giuliano Iacobelli
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
LinkMe Srl
 
Introduction to Python and Django
Introduction to Python and DjangoIntroduction to Python and Django
Introduction to Python and Django
solutionstreet
 
13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS 13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS
DrupalMumbai
 
BackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applicationsBackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applications
Joseph Khan
 

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

GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
 
Why Django for Web Development
Why Django for Web DevelopmentWhy Django for Web Development
Why Django for Web Development
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Django tutorial
Django tutorialDjango tutorial
Django tutorial
 
Introduction Django
Introduction DjangoIntroduction Django
Introduction Django
 
Tango with django
Tango with djangoTango with django
Tango with django
 
Introduction to django
Introduction to djangoIntroduction to django
Introduction to django
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
 
Django interview Questions| Edureka
Django interview  Questions| EdurekaDjango interview  Questions| Edureka
Django interview Questions| Edureka
 
國民雲端架構 Django + GAE
國民雲端架構 Django + GAE國民雲端架構 Django + GAE
國民雲端架構 Django + GAE
 
Django by rj
Django by rjDjango by rj
Django by rj
 
Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)
 
django
djangodjango
django
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
 
Get things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplicationsGet things done with Yii - quickly build webapplications
Get things done with Yii - quickly build webapplications
 
Angular Intermediate
Angular IntermediateAngular Intermediate
Angular Intermediate
 
Introduction to Python and Django
Introduction to Python and DjangoIntroduction to Python and Django
Introduction to Python and Django
 
13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS 13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS
 
Django
DjangoDjango
Django
 
BackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applicationsBackboneJS Training - Giving Backbone to your applications
BackboneJS Training - Giving Backbone to your applications
 

Recently uploaded

AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 

Recently uploaded (20)

AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 

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/