In addition to working with Django admin for testing, you can also get REPL access to your Django environment:
$ python manage.py shell
and do things like test out how to access or filter a model, etc
Same with the db env:
$ python manage.py dbshell
See migations with showmigrations
:
$ python manage.py showmigrations
Or create a migation:
$ python manage.py makemigration
Migrate with migrate
, or roll back a migration by
referencing the migration before it for the given section:
$ pythom manage.py migrate core 002_migation_to_rollback_to
A migration that involves additional processing such as a backfill can
also be done. Create an empty migration and then use
RunPython
:
from django.db import migrations
def run_backfill(apps, schema_editor):
MyModel = apps.get_model('core', 'MyModel')
db_alias = schema_editor.connection.alias
model = MyModel.objects.using(db_alias).get(...)
...
class Migration(migations.Migration):
dependencies = [
('core', '003_backfill')
]
operations = [
migrations.RunPython(run_backfill)
]
Cache reused template objects with {% with ... %}
Use select_related
and prefetch_related
to
prefetch results from joined tables that will be reused in the view
template:
result = Hangout.select_related('hangout__owner')
.select_related('hangout__owner__profile')
.filter(hangout=request.user.hangout)
Django also has some extra support for relational data, such as union, intersection and difference:
queryset1.union(queryset2)
queryset1.intersection(queryset2)
queryset1.difference(queryset2)
Use .query
on queryset objects to debug the actual SQL
statement that's generated.
GROUP BY
SQL created with
.annotate
Production static files are collected with
python manage.py collectstatic
Django's default settings for static files is typically enough for most use cases, but there are times when it makes sense to code something in non-dev mode, such as when customizing error pages
Make the STATIC_URL
property customizable in
settings.py
:
STATIC_URL = os.getenv('DJANGO_STATIC_URL') or '/static/'
An easy to way to serve them is with http-server
:
$ npm i -g http-server
$ http-server staticfiles/
$ DJANGO_STATIC_URL=localhost:8080 python manage.py runserver