检查待处理的Django迁移

编程入门 行业动态 更新时间:2024-10-25 12:20:04
本文介绍了检查待处理的Django迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在Django中,有没有一种简单的方法来检查是否已运行所有数据库迁移?我找到了 manage.py migration --list ,它为我提供了我想要的信息,但是格式不是机器可读的。

In Django, is there an easy way to check whether all database migrations have been run? I've found manage.py migrate --list, which gives me the information I want, but the format isn't very machine readable.

对于上下文:我有一个脚本,该脚本在迁移数据库之前不应该开始运行。由于各种原因,从运行迁移的流程中发送信号会很棘手。因此,我想让我的脚本定期检查数据库,以查看是否所有迁移都已运行。

For context: I have a script that shouldn't start running until the database has been migrated. For various reasons, it would be tricky to send a signal from the process that's running the migrations. So I'd like to have my script periodically check the database to see if all the migrations have run.

推荐答案

Shell

到目前为止,我发现的唯一简单的解决方案就是运行

The only simple solution I've found so far is running

./manage.py showmigrations | grep '\[ \]'

如果所有迁移都已完成,它将输出一个空字符串

which will output an empty string in case all migrations have been applied.

但是,它与输出格式紧密相关。

However, it is closely tied to the output format.

Python

我检查了 migrate 命令,看来应该可以解决问题:

I checked the source code of migrate command and it seems like this should do the trick:

from django.db.migrations.executor import MigrationExecutor from django.db import connections, DEFAULT_DB_ALIAS def is_database_synchronized(database): connection = connections[database] connection.prepare_database() executor = MigrationExecutor(connection) targets = executor.loader.graph.leaf_nodes() return not executor.migration_plan(targets) # Usage example. if is_database_synchronized(DEFAULT_DB_ALIAS): # All migrations have been applied. pass else: # Unapplied migrations found. pass

更多推荐

检查待处理的Django迁移

本文发布于:2023-11-09 20:22:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1573339.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!