预提交挂钩以检查 Django 迁移

pre-commit hook to check django migrations

我正在尝试为我的 Django 项目编写一个 pre-commit 挂钩,以检查缺少的迁移。也就是说,它确保所有更改都反映在迁移文件中。

如果 makemigrations 命令 returns 没有更改,则实现此目的的一种方法是通过预提交挂钩。

$ ./manage.py makemigrations --dry-run
No changes detected

并且如果它 returns 某些东西使预提交挂钩失败:

$ ./manage.py makemigrations --dry-run
Migrations for 'myapp':
  myapp/migrations/0003_auto_20201213_2233.py
    - Alter field type on event

如何编写这个预提交钩子?有没有比使用 makemigrations 更好的方法?这是我到目前为止所拥有的,但它总是通过(我想我需要解析响应):

repos:
  - repo: local
    hooks:
      - id: pre-commit-django-migrations
        name: Check django migrations
        entry: ./manage.py makemigrations --dry-run
        language: system
        types: [python]
        pass_filenames: false

来自 Django makemigrations documentation

--check

Makes makemigrations exit with a non-zero status when model changes without migrations are detected.

所以你可以使用--check来代替

  entry: python manage.py makemigrations --check