Skip to content

Instantly share code, notes, and snippets.

@fodra
Last active May 31, 2018 04:55
Show Gist options
  • Save fodra/cfcf6fc72328d1d76d915e0e7521444a to your computer and use it in GitHub Desktop.
Save fodra/cfcf6fc72328d1d76d915e0e7521444a to your computer and use it in GitHub Desktop.
Notes on Django
  1. Create an empty django migration

python manage.py makemigrations --empty yourappname

  1. Show applied migrations

python manage.py showmigrations <app_name>

  1. Rollback migration to a specific state

python manage.py migrate <app_name> <desired_migration_state.py>

  1. Delete all objects in the table

Post.objects.all().delete()

  1. Filter rows where a field is not null

Post.objects.filter(title__isnull=False)

  1. Use first instead of get so it returns None if it does not exist

post = Post.objects.filter(id=1).first()

  1. Count the foreign key elements.

Post.objects.annotate(num_articles=Count('article')).filter(num_articles__gt=1)

  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

Articles

  1. Designing better models
  1. Testing emails sent
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment