Dm的Python的驱动包都在安装目录(D:\dmdbms\drivers\python)下, 根据用到的django版本选择不同的django_dmPythonX.0.0的安装包
在安装django_dmPythonX.0.0的安装包前需要先安装dmPython包
# 方法一: 可查看目录下的readme.txt文本,windows和linux也可以直接使用源码安装,这里的话本地不安装达梦库可能会报很多错,请查看博客其他的文章
# 操作如下:
1.进入到dmPython源码所在目录(setup.py文件所在路径)
2.执行命令:python setup.py install
# 方法二: pip_search dmPython 进行安装,这里不建议使用这种,最好还是使用数据库下相同版本的数据库驱动
PS D:\Python\Python39> pip_search dmPython
https://pypi.org/search/?q=dmPython
┌────────────────────┬──────────────────┬────────────┬────────────────────────────────────┐
│ Package │ Version │ Released │ Description │
├────────────────────┼──────────────────┼────────────┼────────────────────────────────────┤
│ dmPython │ 8.1.2.98 > 2.4.9 │ 28-04-2022 │ Python interface to Dameng │
│ django-dmPython │ 3.1.7 > 3.0.1 │ 28-04-2022 │ Dameng database backend for Django │
└────────────────────┴──────────────────┴────────────┴────────────────────────────────────┘
# 方法一: 可查看目录下的readme.txt文本,windows和linux也可以直接使用源码安装,操作如下:
1.进入到django_dmPython3.0.0源码所在目录(setup.py文件所在路径)
2.执行命令:python setup.py install
# 方法二: pip_search dmPython 进行安装,这里不建议使用这种,最好还是使用数据库下相同版本的数据库驱动
PS D:\Python\Python39> pip_search django_dmPython
│ django-dmPython │ 3.1.7 > 3.0.1 │ 28-04-2022 │ Dameng database backend for Django
│ dmPython │ 8.1.2.98 > 2.4.9 │ 28-04-2022 │ Python interface to Dameng
## 安装django框架
$ pip install django==4.1.0
## 查询安装的相关版本,注:使用 pip serch里面的版本可能会出现项目运行报错的情况
$ pip list
Package Version
------------------------- ---------
Django 4.1
django-dmPython 3.0.1
dmpython 2.4.9
#在INSTALLED_APP属性中新增应用模块,默认会自己创建
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
##新增应用模块
'dameng_conn.apps.DamengConnConfig',
]
# 将原来默认的sqlite的连接串去掉 换成达梦的信息
# DATABASES = {
# "default": {
# "ENGINE": "django.db.backends.sqlite3",
# "NAME": BASE_DIR / "db.sqlite3",
# }
# }
DATABASES = {
'default': {
'ENGINE': 'django_dmPython',
'NAME': 'DAMENG',
'USER': 'SYSDBA',
'PASSWORD': 'SYSDBA',
'OPTIONS': {'schema': 'DJANGGO'},
'HOST': '10.15.1.18',
'PORT': '5236',
}
}
进入 dameng_conn/views.py 文件创建视图:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def applist(request):
return HttpResponse("Hello, DM Database")
进入 dameng_conn/views.py 文件设置应用访问路由:
from . import views
from django.urls import path
## 设置应用访问路由
urlpatterns = [
path('', views.applist, name='listapp'),
]
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path("admin/", admin.site.urls),
path('dameng_conn/', include('dameng_conn.urls')),
]
Django 作为 web 开发框架,其内部已经包含有 ORM(object relational mapping)组件,在创建好模型后,对应模块将对象属性值转换成相应的SQL语句自动在数据库中执行,此时的类属性就相当于表字段。
from django.db import models
# Create your models here.
from django.db import models
# Create your models here.
from django.db import models
class Menu(models.Model):
name = models.CharField('英文名', max_length=255, unique=True)
label = models.CharField('中文名', max_length=255)
parent = models.ForeignKey(to='self', on_delete=models.CASCADE, verbose_name='上级菜单', blank=True, null=True)
class Meta:
verbose_name = '菜单'
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class Department(models.Model):
name = models.CharField('名字', max_length=64)
order_no = models.IntegerField('排序', default=100, help_text='小的排前面')
remark = models.CharField('备注', max_length=256, blank=True, null=True)
status = models.BooleanField('状态', choices=((True, '启用'), (False, '停用')), default=True)
parent = models.ForeignKey(to='self', on_delete=models.CASCADE, verbose_name='上级部门', blank=True, null=True)
create_time = models.DateTimeField('创建时间', auto_now_add=True)
# 递归展示部门名字
def recursive_name_function(self, mi, temp=''):
"""
recursive name
:param mi: model instance
:param temp: temporary name(do not pass this parameter !!!)
:return: recursive name
"""
return self.recursive_name_function(mi.parent, f'/{mi.name}{temp}') if mi.parent else f'{mi.name}{temp}'
def recursive_name(self):
return self.recursive_name_function(self)
recursive_name.short_description = '名字'
class Meta:
verbose_name = '部门'
verbose_name_plural = verbose_name
ordering = ['-status', 'order_no']
def __str__(self):
return self.name
# Create your models here.
class MyProject(models.Model):
# 项目表:
table_name = models.AutoField(primary_key=True, db_column='MY_PROJECT_INFO')
# 项目编号:
project_id = models.IntegerField(null=True)
# 项目名称:
project_name = models.CharField(max_length=100)
# 项目地址:
project_address = models.CharField(max_length=200)
# 项目联系人姓名:
project_contact = models.CharField(max_length=200)
# 项目联系人电话:
phone_number = models.CharField(max_length=200)
# 项目描述:
project_description = models.TextField(null=True)
# 操作系统版本:
os_version = models.CharField(max_length=200)
# CPU核数:
cpu_num = models.IntegerField(null=True)
# 内存大小:
memory_size = models.IntegerField(null=True)
# 磁盘大小:
disk_size = models.IntegerField(null=True)
# 表名:
class Meta:
db_table = 'MY_PROJECT_INFO'
class Role(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class CustomUser(models.Model):
# 项目表:
userid = models.AutoField(primary_key=True)
username = models.CharField(max_length=100, unique=True, verbose_name='用户名')
remark = models.CharField(verbose_name='备注', max_length=256, blank=True, null=True)
nickname = models.CharField(verbose_name='昵称', max_length=64, blank=True, null=True)
role = models.ForeignKey(Role, on_delete=models.CASCADE, related_name='users', related_query_name='user', null=True)
def __str__(self):
return self.username
# 表名:
class Meta:
db_table = 'ACCOUNTS_CUSTONUSER'
dameng_conn/management/commands/init_data.py
from dameng_conn.models import Role, CustomUser
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Initialize roles and users'
def handle(self, *args, **options):
# 初始化角色
roles = ['Admin', 'User', 'Guest']
for role in roles:
Role.objects.create(name=role)
# 初始化用户
users = [
{
'username': 'admin',
'remark': 'Administrator',
'nickname': 'Admin',
'role_name': 'Admin'
},
{
'username': 'john',
'remark': 'Regular User',
'nickname': 'John',
'role_name': 'User'
}
]
for user_data in users:
role_name = user_data.pop('role_name')
role = Role.objects.get(name=role_name)
CustomUser.objects.create(role=role, **user_data)
self.stdout.write(self.style.SUCCESS('Roles and users initialized successfully.'))
PS E:\PythonCode\djangoProject> python manage.py makemigrations dameng_conn
Migrations for 'dameng_conn':
dameng_conn\migrations\0001_initial.py
- Create model MyProject
- Create model Role
- Create model Menu
- Create model Department
- Create model CustomUser
PS E:\PythonCode\djangoProject> python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, dameng_conn, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying dameng_conn.0001_initial... OK
Applying sessions.0001_initial... OK
PS E:\PythonCode\djangoProject>
Django的makemigrations和migrate命令只负责数据库结构的迁移,而不涉及数据的初始化。
python manage.py makemigrations和python manage.py migrate是Django的管理命令,用于执行数据库迁移操作。
通过运行这两个命令,你可以将在models.py中对数据库的改变应用到实际的数据库中。首先,运行python manage.py makemigrations命令来生成迁移文件,然后再运行python manage.py migrate命令将这些改变应用到数据库中。
PS E:\PythonCode\djangoProject> python manage.py init_data
Roles and users initialized successfully.
链接:https://pan.baidu.com/s/1fF5DXJ4hTF-wlkByghPvyw?pwd=lwy4 提取码:lwy4