Current Django Version: 3.0
Methods that return new QuerySets
Dajngo uses MVC system : Model - View - Controllers
python -m venv venv
create a virtual encironment
source venv/bin/activate
activate virtual environment venv
pip install -r requirements.txt
install all the required tools
createdb db_name
django-admin startproject <name> .
This makes sure that the project is not nested
mysite/ --> A container for your project/ can be renamed.
manage.py --> A command-line utility that lets you interact with this Django project.
mysite/. --> Actual Python package for your project
__init__.py --> An empty file that tells Python that this directory should be considered a Python package.
settings.py --> Settings/configuration for this Django project.
urls.py. --> The URL declarations for this Django project; a “table of contents” of your Django-powered site.
asgi.py --> An entry-point for ASGI-compatible web servers to serve your project.
wsgi.py --> An entry-point for WSGI-compatible web servers to serve your project.`
python manage.py runserver
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
python manage.py runserver 8080
python manage.py runserver 0:8000
python manage.py startapp name
The migrate command looks at the INSTALLED_APPS setting and creates any necessary database tables according to the database settings in your project/settings.py file and the database migrations shipped with the app (Next migrations will completed after the models are ceated, look at #7).
python manage.py migrate
python manage.py createsuperuser
Models are Python objects that define the structure of an application's data, and provide mechanisms to manage (add, modify, delete) and query records in the database. Here, each model is represented by a class that subclasses django.db.models.Model. Each model has a number of class variables, each of which represents a database field in the model.
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
The model code gives Django a lot of information. With it, Django is able to: a. Create a database schema (CREATE TABLE statements) for this app. b. Create a Python database-access API for accessing Question and Choice objects. after telling the project that the app is installed in the project INSTALLED_APPS section in settings.
python manage.py makemigrations <app_name>
, then run
python manage.py migrate <app_name>
A view is a request handler function, which receives HTTP requests and returns HTTP responses.
Views access the data needed to satisfy requests via models, and delegate the formatting of the response to templates.
from django.http import HttpResponse
def index(request):
`return HttpResponse()`
While it is possible to process requests from every single URL via a single function, it is much more maintainable to write a separate view function to handle each resource. A URL mapper is used to redirect HTTP requests to the appropriate view based on the request URL. The URL mapper can also match particular patterns of strings or digits that appear in a URL and pass these to a view function as data.
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
When Django encounters include(), it chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing. URLconf is like a table of contents for your Django-powered Web site.
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
python manage.py runserver
Add'APP_name', 'django_extensions' under INSTALLED_APPS
If you are not using SQLite as your database, additional settings such as USER, PASSWORD, and HOST
`DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'mydatabase'
}
}`
Now, let’s hop into the interactive Python shell and play around with the free API Django gives you. To invoke the Python shell, use this command:
python manage.py shell_plus
It’s important to add str() methods to your models, not only for your own convenience when dealing with the interactive prompt, but also because objects’ representations are used throughout Django’s automatically-generated admin.
class Choice(models.Model):
# ...
def __str__(self):
return self.choice_text
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
A template is a text file defining the structure or layout of a file (such as an HTML page), with placeholders used to represent actual content. A view can dynamically create an HTML page using an HTML template, populating it with data from a model. A template can be used to define the structure of any type of file; it doesn't have to be HTML!
Other commands:
- Create Database
- Set up your models
- Run makemigrations `
- Run python manage.py migrate
- If you make alterations to models, rerun the migrations commands to update db.
- Tests to pass: python manage.py test --failfest
python manage.py shell_plus
to complete commands in the py shell
python -m venv venv
create a virtual encironment
source venv/bin/activate
activate virtual environment venv
pip install -r requirements.txt
install all the
django-admin.py startproject <project_name>
start a new Django project
git init
Initialize new Git repo
git add -A
add your changes to staging and then to the local repo.
git commit -am
initial commit
git remote add origin
PUSH your files to central repo.
git remote add origin github.com/Carole-Ouedraogo/new_repo
git push -u origin master
createdb <db_name>
python3 manage.py test
python3 manage.py migrate
python3 manage.py makemigrations <app_name>
python manage.py test --failfest
test file is run
new_var = _
assigns, and gives you access to previous output in python shell
ON DELETE CASCADE
delete child when parent is deleted
ON DELETE SET NULL
set null when parent is deleted
Can be chained:
Entry.objects.filter(**kwargs).exclude(**kwargs).order_by(**kwargs)
- filter
- exclude
- annotate
- order_by
- reverse
- distinct
- values
- values_list
- dates
- datetimes
- none
- all
- union
- intersection
- difference
- select_related
- prefetch_related
- extra
- defer
- only
- using
- select_for_update
- raw
Operators that return new QuerySets
Methods that do not return QuerySets
- get
- create
- get_or_create
- update_or_create
- bulk_create
- bulk_update
- count
- in_bulk
- iterator
- latest
- earliest
- first
- last
- aggregate
- exists
- update
- delete
- as_manager
- explain
Field lookups are how you specify the meat of an SQL WHERE clause. They’re specified as keyword arguments to the QuerySet methods filter(), exclude() and get().
Example: Entry.objects.get(id__exact=14) # note double underscore.
- exact
- iexact
- contains
- icontains
- in
- gt
- gte
- lt
- lte
- startswith
- istartswith
- endswith
- iendswith
- range
- date
- year
- iso_year
- month
- day
- week
- week_day
- quarter
- time
- hour
- minute
- second
- isnull
- regex
- iregex
Protip: Use in to avoid chaining filter() and exclude()
Entry.objects.filter(status__in=['Hung over', 'Sober', 'Drunk'])
Aggregation functions (link)
Query-related tools (link)
Django-QuerySet-Cheatsheet by @chrisdl and @briandant is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
The contributors are as gods among ants and shall forever be remembered as such.
The Django web framework referenced in the Django-QuerySet-Cheatsheet is © 2005-2018 Django Software Foundation. Django is a registered trademark of the Django Software Foundation.