django apps and orm beyond the basics [meetup hosted by prodeers.com]
TRANSCRIPT
ABOUT ME
I WEAR MULTIPLE HATSSOFTWARE DEVELOPER
PRODUCT MANAGERENTREPRENEUR
I LOVE TO TRAVELMY 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 ARCHITECTUREDjango 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
• Discus
• Spotify
• Washington Post
• Firefox
• NASA
• BitBucket
• Prezi
• EventBrite
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 \app\bin\activate
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
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
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.
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
There are several commands which you will use to interact with migrations:•migrate, which is responsible for applying migrations, as well as unapplying and listing their status.•makemigrations, which is responsible for creating new migrations based on the changes you have made to your models.•sqlmigrate, which displays the SQL statements for a migration.•showmigrations, which lists a project’s migrations.
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.)
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)
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/