Django之使用mysql

发布于 2018-06-09  232 次阅读


首先修改settings.py

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'databaseName', #数据库名
'USER': 'root', #用户名
'PASSWORD': 'your password',
'HOST': '111.111.111.111',
'PORT': '3306',
'CHARSET':'utf8',##设置字符集,不然会出现中文乱码
'OPTIONS': {
'init_command': "SET sql_mode ='STRICT_TRANS_TABLES' "
}
}
}

然后新建models.py为创建表,一般项目自带有,因为Django的orm框架是code first原则

此处有个BaseModel作为基类 要设置abstract防止生成表,db_table是设置表名

from django.db import models
class BaseModel(models.Model):
    id = models.AutoField(db_column='Id', primary_key=True)  # Field name made lowercase.
    createdatetime = models.DateTimeField(db_column='CreateDateTime',default=timezone.now)  # Field name made lowercase.
    modifydatetime = models.DateTimeField(db_column='ModifyDateTime',default=timezone.now)
    creator = models.IntegerField(db_column='Creator',blank=True, null=True)  # Field name made lowercase.
    modifier = models.IntegerField(db_column='Modifier',blank=True, null=True)  # Field name made lowercase.

    class Meta:
        abstract = True

class SysDepartment(BaseModel):
    description = models.CharField(db_column='Description', max_length=100)  # Field name made lowercase.
    leader = models.CharField(db_column='Leader', max_length=20)  # Field name made lowercase.
    name = models.CharField(db_column='Name', max_length=20)  # Field name made lowercase.
    parentid = models.IntegerField(db_column='ParentId')  # Field name made lowercase.
    def __str__(self):
        return self.name
    class Meta:
        db_table = 'Sys_Department'

执行生成迁移文件命令

manage.py makemigrations

可以设置参数为生成指定app的迁移文件

manage.py makemigrations app_name

执行迁移

manage.py migrate

精确到app

manage.py migrate app_name

精确到迁移文件

manage.py migrate app_name 0004

执行完数据库中就会多出这些表

 

还有,从以有数据库的表生成对应的models文件

运行下面代码可以自动生成models模型文件
manage.py inspectdb
这样就可以在命令行看到数据库的模型文件了

把模型文件导入到app中
创建一个app
manage.py inspectdb > app/models.py

然后就是如何使用models的managers

每个继承models.Model的子类都有个属性objects

这个objects有很多方法

官网文档:点击前往

另一个是cnblog一位博主写的也挺详细:点击前往

也可以自己重写,继承自models.Manager

class SysDepartmentManager(models.Manager):
def get_by_id(self,id):
a = super().get_queryset().filter(id=id)
return a

然后修改对应的model中objects属性,也可以自己新加个属性例如manager

class SysDepartment(BaseModel):
     description = models.CharField(db_column='Description', max_length=100)
     leader = models.CharField(db_column='Leader', max_length=20)
     name = models.CharField(db_column='Name', max_length=20)
     parentid = models.IntegerField(db_column='ParentId')
     def __str__(self):
          return self.name
     class Meta:
     db_table = 'Sys_Department'
     objects = SysDepartmentManager()
     manager = SysDepartmentManager()

调用方式

SysDepartment.objects.get_by_id(1)
SysDepartment.manager.get_by_id(1)

LoneKing