Migration

python manage.py migrate --fake yourproject 0041 # Mark the migration as it is there.
style = models.CharField(default='classic')

Django’s default for a Field is not set into Database column. It will be set by Django’s code.

So when we see this in migration script:

migrations.AddField(
    model_name='project',
    name='style',
    field=models.CharField(default='classic', max_length=20),
    preserve_default=False,
),

The preserve_default is False, so it is one-off code (more info: Django migration-operations).

Many to Many

  • A ManyToMany field, now you want to make it through a model, how to make it? https://stackoverflow.com/questions/26927705/django-migration-error-you-cannot-alter-to-or-from-m2m-fields-or-add-or-remove

https://adriennedomingus.com/blog/django-adding-an-intermediate-model-to-a-manytomany-field-without-one

inspectdb

DB optimization

https://docs.djangoproject.com/en/3.1/topics/db/optimization/

https://docs.djangoproject.com/en/3.1/faq/models/#faq-see-raw-sql-queries

Kill n + 1 query

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#prefetch-related

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.prefetch_related_objects

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#prefetch-objects

https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.defer

#####

from itertools import chain
queryset = queryset.filter(
    github_account_id__in=chain(self.get_committer_ids(), self.get_reviewer_ids())
)

Here chain need the value of self.get_committer_ids() and self.get_reviewer_ids(). That means database query will be invoked immediately after self.get_committer_ids() and self.get_reviewer_ids(). Invoked 2 times.

union can help us avoid this problem.