Django

137 flashcards by MentisLibrary

The framework end to end: projects and apps, models and the ORM's query API, migrations, views and URLs, templates, forms and validation, authentication, the admin, and testing a Django site.

What is Django?
A high-level Python web framework that ships with an ORM, URL routing, a template engine, forms, authentication and an admin site, following a batteries-included philosophy.
Project vs app in Django
A project is the whole site configuration (settings, root URLconf); an app is a Python package that does one thing, such as blog or accounts, and can be reused across projects.
What does manage.py do?
A thin wrapper around django-admin that sets DJANGO_SETTINGS_MODULE to your project's settings before running a management command.
The MTV pattern
Django's version of MVC: Model (data and rules), Template (presentation), View (which data to show for a request). The URL dispatcher plays the controller role.
What is INSTALLED_APPS?
The settings list of app configs Django loads; it decides which models get tables, which templates/ and static/ directories are searched, and which management commands exist.
Which settings must change before a Django site goes to production?
Set DEBUG = False, fill in ALLOWED_HOSTS, load SECRET_KEY from the environment instead of the file, and point DATABASES at a real server.
What is SECRET_KEY used for?
Cryptographic signing: session cookies, CSRF tokens, password reset tokens, signing.dumps() and messages cookies.
USE_TZ and TIME_ZONE
With USE_TZ = True Django stores datetimes in UTC and converts to TIME_ZONE for display; timezone.now() returns an aware datetime.
How do you define a model?
Subclass django.db.models.Model and declare fields as class attributes. Each class maps to one table and each field to one column.
CharField vs TextField
CharField requires max_length and maps to VARCHAR; TextField is unbounded and maps to TEXT.
auto_now vs auto_now_add
auto_now_add=True sets the field once when the row is first created; auto_now=True overwrites it on every save().
What is a ForeignKey?
A many-to-one relation. The column stores the related row's primary key, and the on_delete argument is required.
What do the on_delete options do?
CASCADE deletes dependents, PROTECT raises ProtectedError, SET_NULL nulls the column (needs null=True), SET_DEFAULT and SET(value) assign, RESTRICT blocks unless the parent is itself being cascaded, DO_NOTHING leaves it to the database.
What is a ManyToManyField?
A relation where each side can have many of the other; Django creates a hidden join table with two foreign keys.
What is a OneToOneField?
A foreign key with unique=True; the reverse accessor returns a single object, not a manager.
null=True vs blank=True
null is database-level (the column accepts NULL); blank is validation-level (forms and the admin may leave it empty).
How do choices work on a field?
An iterable of (value, label) pairs that restricts the field in forms and gives the model a get_<field>_display() method; TextChoices and IntegerChoices enums are the modern form.
What goes in a model's class Meta?
Options that are not fields: ordering, verbose_name, db_table, constraints, indexes, unique_together, abstract, permissions.
Why define __str__ on a model?
It is the label Django uses in the admin, the shell, select boxes and error messages.
What is get_absolute_url()?
A model method returning the canonical path for an object; the admin's View on site link, redirect(obj) and CreateView all use it.
UniqueConstraint in Meta.constraints
Declares a database-level uniqueness rule over one or more columns, optionally with a condition.
How do you override save() on a model?
Define save(self, *args, **kwargs), do your work, then call super().save(*args, **kwargs).
What is a migration?
A Python file in app/migrations/ describing a schema or data change. Django generates it from model diffs and applies it in order, recording progress in the django_migrations table.
makemigrations vs migrate
makemigrations writes migration files from model changes; migrate runs unapplied migrations against the database, or moves to a named migration.
What is a data migration?
A migration that changes rows instead of schema, written with migrations.RunPython(forward, reverse).
showmigrations and sqlmigrate
showmigrations lists every migration with [X] for applied ones; sqlmigrate app 0002 prints the SQL a migration would execute.
What is a QuerySet?
A lazy, chainable description of a database query. No SQL runs until you iterate, slice, or call a terminal method such as count() or first().
What is objects on a model?
The default Manager, the entry point for every query on that model.
filter() vs exclude() vs get()
filter() returns a QuerySet of matches, exclude() the complement, and get() returns exactly one model instance.
What are field lookups?
Double-underscore suffixes on a field name that select the SQL operator: exact, iexact, contains, icontains, startswith, in, gt, gte, lt, lte, range, isnull, year, date.