- Create an empty django migration
python manage.py makemigrations --empty yourappname
- Show applied migrations
python manage.py showmigrations <app_name>
- Rollback migration to a specific state
python manage.py migrate <app_name> <desired_migration_state.py>
- Delete all objects in the table
Post.objects.all().delete()
- Filter rows where a field is not null
Post.objects.filter(title__isnull=False)
- Use first instead of get so it returns None if it does not exist
post = Post.objects.filter(id=1).first()
- Count the foreign key elements.
Post.objects.annotate(num_articles=Count('article')).filter(num_articles__gt=1)
- Solving circular imports
- prefer import Library vs from Library import SomeObject
- Better: field = models.ForeignKey('app.SomeObject', on_delete=models.CASCADE), instead of specifying the class itself, you can pass a string
- Designing better models
- Testing emails sent