用于检查 django 迁移的预提交钩子

问题描述 投票:0回答:2

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

实现此目的的一种方法是,如果

makemigrations
命令未返回任何更改,则通过预提交挂钩。

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

如果预提交挂钩返回某些内容,则它会失败:

$ ./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 pre-commit-hook pre-commit pre-commit.com
2个回答
9
投票

来自 Django

makemigrations
文档

--check

当模型更改时,使 makemigrations 以非零状态退出 没有检测到迁移。

因此您可以将

--check
--dry-run
一起使用:

  entry: python manage.py makemigrations --check --dry-run

0
投票

您可以使用pre-commit-hooks-django,例如:

-   repo: https://github.com/ecugol/pre-commit-hooks-django
    rev: v0.4.0  # Use the ref you want to point at
    hooks:
    -   id: check-untracked-migrations
        # Optional, if specified, hook will work only on these branches
        # otherwise it will work on all branches
        args: ["--branches", "main", "other_branch"]
    -   id: check-unapplied-migrations
    -   id: check-absent-migrations
© www.soinside.com 2019 - 2024. All rights reserved.