如何将Django model注释迁移到数据库?

1,692 阅读1分钟

在django中,定义好的model默认是没有办法去修改或者添加注释的,但是我们又不可能手动的去给数据库的表字段添加注释,因为在真实开发中有多个环境,每个环境的数据库的注释需要保持一致,手动添加或修改注释比较麻烦,而且容易错误。

本文介绍一个Django插件来自动将Django model的help_text当做注释迁移到数据库中,具体使用方法如下:

  1. 安装插件
    pip install django-comment-migrate
    
  2. 添加 django_comment_migrate app project/project/settings.py:
    INSTALLED_APPS =[
    "django_comment_migrate",
     ...
    ]
    
    
  3. 添加 model project/app/model.py
    from django.db import models
    
    class CommentModel(models.Model):
        no_comment = models.TextField()
        aaa = models.IntegerField(default=0, help_text="test default")
        help_text = models.CharField(max_length=40,
                                     help_text="this is help text")
    
        class Meta:
            app_label = 'tests'
            db_table = 'comment_model'
    
  4. 执行数据库迁移:
    python manage.py makemigrations 
    python manage.py migrate
    

现在检查数据库中的表,就会看到生成的注释了。

命令

django-comment-migrate插件还提供了一个命令重新生成注释,主要用在已经执行过迁移了,需要把历史的model也生成下注释,这时候就需要用到这条命令了:

python manage.py migratecomment [app_label]

注意: 一定要先执行 migrate后,在执行这条命令,否则会出现意料之外的错误,虽然不影响结果。

总结

django-comment-migrate插件的用法就介绍到这里了,更多详细的用法请看github地址: github.com/starryrbs/d…