Skip to content

Django

Getting Started

Easy Guide to Follow

Settings

Structure

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    # 3rd party
    "rest_framework",
    # Local
    "books.apps.BooksConfig",

Models

Set up data structure.

  • can make use of a str method to display model instance in a more readable format
def __str__(self):
        return self.title
  • for user models extend the AbstractUser class
    • settings.py then needs updated to point the custom user class at AUTH_USER_MODEL
  • don't use blank=True on FK relation definitions

Views

Control and customize how the database model content is displayed in the template.

  • have different types of views like ListView
  • can get a dictionary of primary keys to model instances
    python
    Model.objects.in_bulk()

Queries

  • use .get over .filter when looking for one specific instance
  • when working with queries that utilized prefetch_related() the best practice for refreshing or updating instance data is to perform another queryset.get() over a refresh_from_db()
    • both clear caches but queryset.get() repopulates using optimized prefetch queries

Lazy Evaluation

When a queryset is created the initial results are not cached and reused when other operations are evaluated. For example

python
  versions = policy.versions.filter(
      field1='value'
  ).exclude(
      field2='value'
  ).exclude(
      field3='value'
  )
  #versions will be set to the filter and exclusion values for the current set of versions

  method_call(versions)

  versions_2 = versions.exclude(field4='value')
  # versions may have been altered in `method_call` when this exclusions call occurs it will refilter using the initial 2 exclusions + the new field4 exclusion

### Exclude
- to use AND queries follow this format
```py
).exclude(
  id=version.id,
  transaction_type='renewal',
  transaction_effective_date__isnull=True
)
  • to not use AND queries follow this format
py
).exclude(
    id=version.id
).exclude(
    transaction_type='renewal'
).exclude(
    transaction_effective_date__isnull=True
)
  • both are only 1 query

Tips

  • python manage.py check can be ran to check server status