Appearance
Django
Getting Started
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
AbstractUserclasssettings.pythen needs updated to point the custom user class atAUTH_USER_MODEL
- don't use
blank=Trueon 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 instancespython
Model.objects.in_bulk()
Queries
- use
.getover.filterwhen 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 anotherqueryset.get()over arefresh_from_db()- both clear caches but
queryset.get()repopulates using optimized prefetch queries
- both clear caches but
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 checkcan be ran to check server status
