Create a model:
- Regularly create models
-
Configure the database information in the setting.py file
# Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': MYSQL_ADDRESS_PRO, 'PORT': '3306', 'NAME': 'db_name', 'USER': MYSQL_ACCOUND_PRO, 'PASSWORD': MYSQL_PASS_PRO, } }
-
Create new models in the models.py file in your django-app
from django.db import models class ZkysBaseModel(models.Model): # 所有model都有的字段,基类 is_delete = models.BooleanField(default=False, db_index=True) c_time = models.DateTimeField(auto_now_add=True) u_time = models.DateTimeField(auto_now=True) # 类中在定义一个类就代表是配置,约定俗成都叫Meta class Meta: # 基表必须设置abstract,基表就是给普通Model类继承使用的,设置了abstract就不会完成数据库迁移完成建表 abstract = True class NotDeletedManager(models.Manager): """ @description :重写模型管理器的getqueryset方法,这样get请求就自动过滤掉is_delete为True 的字段了,sure,你可以可以定义你自己的规则。 --------- @param : ------- @Returns : ------- """ def get_queryset(self): return models.Manager.get_queryset(self).filter(is_delete=False) class BladeNumberTableModel(ZkysBaseModel): task_id = models.CharField(unique=True, max_length=50, blank=True, null=True) blade_one = models.CharField(max_length=255, default="", help_text='') blade_two = models.CharField(max_length=255, default="", help_text='') blade_three = models.CharField(max_length=255, default="", help_text='') # 添加逻辑外键,不改变mysql的表结构,但是可以用orm关联查询,db_constraint=False就是实现了这个功能 fault_type_code = models.ForeignKey(to='FaultTypeManage', to_field='fault_type_code', on_delete=models.SET_NULL, db_constraint=False, null=True, blank=True, db_column="fault_type_code") objects = NotDeletedManager() class Meta: managed = True db_table = 'blade_number_table'
-
-
Convert existing database structure to model in Django
-
python .\manage.py inspectdb > my_modela_app/models.py The automatically generated model may be different from the actual one, but it doesn’t matter, it will be resolved during the first migration
-
python .\manage.py makemigrations generate migration files
-
python .\manage.py migrate --fake Because it is a transferred model, normal migration will definitely report an error, and I hope django thinks this is the result of the existing database, so add --fake for the first migration (the database ignores this times migrate)
-
The subsequent operations will be the same as the normal operation model orm process
-
Registering django_comment_migrate in install_app during migration will help us arrange the field comments in the model into the mysql table
-