添加代码

master
roger 1 year ago
parent 1cc22e8a1d
commit 3a740368a0
  1. 0
      django_demo/__init__.py
  2. 16
      django_demo/asgi.py
  3. 130
      django_demo/settings.py
  4. 21
      django_demo/urls.py
  5. 16
      django_demo/wsgi.py
  6. 0
      orm_demo/__init__.py
  7. 3
      orm_demo/admin.py
  8. 6
      orm_demo/apps.py
  9. 77
      orm_demo/migrations/0001_initial.py
  10. 0
      orm_demo/migrations/__init__.py
  11. 65
      orm_demo/models.py
  12. 36
      orm_demo/orm_crud.py
  13. 3
      orm_demo/tests.py
  14. 3
      orm_demo/views.py

@ -0,0 +1,16 @@
"""
ASGI config for django_demo project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_demo.settings')
application = get_asgi_application()

@ -0,0 +1,130 @@
"""
Django settings for django_demo project.
Generated by 'django-admin startproject' using Django 4.1.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-c_2hx*fl5x=#lyu8ap665y)cvczlob78oq&u_#f^mc@fycxfp+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'orm_demo.apps.OrmDemoConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_demo.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_demo.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'HOST': 'home.rogersun.cn',
'USER': 'root',
'PASSWORD': 'Sxzgx1209',
'PORT': '3306',
'NAME': 'django_demo',
}
}
DJANGO_SETTINGS_MODULE = []
# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

@ -0,0 +1,21 @@
"""django_demo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]

@ -0,0 +1,16 @@
"""
WSGI config for django_demo project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_demo.settings')
application = get_wsgi_application()

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

@ -0,0 +1,6 @@
from django.apps import AppConfig
class OrmDemoConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'orm_demo'

@ -0,0 +1,77 @@
# Generated by Django 4.2.3 on 2023-07-07 06:50
from django.db import migrations, models
import django.db.models.deletion
import orm_demo.models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BaseUserInfo',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, verbose_name='编号')),
('username', models.CharField(max_length=30, verbose_name='用户名')),
('password', models.CharField(max_length=20, verbose_name='密码')),
('status', models.CharField(max_length=1, verbose_name='状态')),
('create_date', models.DateField(auto_now_add=True, db_column='createDate', verbose_name='创建日期')),
],
options={
'db_table': 'orm_user_base_info',
'db_table_comment': '人员基本信息',
},
),
migrations.CreateModel(
name='DepartInfo',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, verbose_name='部门编号')),
('depart_name', models.CharField(max_length=30, verbose_name='部门名称')),
('create_date', models.DateField(auto_now_add=True, db_column='createDate', verbose_name='创建日期')),
],
options={
'db_table': 'orm_depart_info',
'db_table_comment': '部门信息',
},
),
migrations.CreateModel(
name='UserExtendInfo',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, verbose_name='扩展编号')),
('username', models.CharField(max_length=30, verbose_name='用户名')),
('true_name', models.CharField(max_length=30, verbose_name='真实姓名')),
('sex', models.IntegerField(verbose_name='性别')),
('age', models.IntegerField(validators=[orm_demo.models.age_validator], verbose_name='年龄')),
('department', models.CharField(max_length=20, verbose_name='部门')),
('salary', models.DecimalField(decimal_places=2, max_digits=8, verbose_name='薪水')),
('status', models.CharField(db_comment='1 有效, 0 无效', max_length=1, verbose_name='状态')),
('create_date', models.DateField(auto_now_add=True, db_column='createDate', verbose_name='创建日期')),
('last_update_time', models.DateTimeField(auto_now=True, db_column='lastUpdateTime', verbose_name='最后更新时间')),
('memo', models.TextField(blank=True, null=True, verbose_name='备注')),
('depart', models.ForeignKey(default='', on_delete=django.db.models.deletion.DO_NOTHING, to='orm_demo.departinfo')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='orm_demo.baseuserinfo')),
],
options={
'db_table': 'orm_user_extend_info',
'db_table_comment': '人员扩展信息',
},
),
migrations.CreateModel(
name='SkillInfo',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, verbose_name='技能编码')),
('skill_name', models.CharField(max_length=30, verbose_name='特长')),
('create_date', models.DateField(auto_now_add=True, db_column='createDate', verbose_name='创建时间')),
('user', models.ManyToManyField(db_table='orm_user_skill', to='orm_demo.userextendinfo')),
],
options={
'db_table': 'orm_skill_info',
'db_table_comment': '技能信息',
},
),
]

@ -0,0 +1,65 @@
from django.db import models
from django.core.exceptions import ValidationError
def age_validator(value):
if value < 0:
raise ValidationError('年龄错误太小了')
if value > 150:
raise ValidationError('太老了,还是人吗?')
class BaseUserInfo(models.Model):
id = models.AutoField(verbose_name='编号', primary_key=True)
username = models.CharField(verbose_name='用户名', max_length=30)
password = models.CharField(verbose_name='密码', max_length=20)
status = models.CharField(verbose_name='状态', max_length=1)
create_date = models.DateField(verbose_name='创建日期', auto_now_add=True, db_column='createDate')
def __str__(self):
return str(self.id) + '-' + self.username
class Meta:
db_table = 'orm_user_base_info'
db_table_comment = '人员基本信息'
class DepartInfo(models.Model):
id = models.AutoField(verbose_name='部门编号', primary_key=True)
depart_name = models.CharField(verbose_name='部门名称', max_length=30)
create_date = models.DateField(verbose_name='创建日期', db_column='createDate', auto_now_add=True)
class Meta:
db_table = 'orm_depart_info'
db_table_comment = '部门信息'
class UserExtendInfo(models.Model):
id = models.AutoField(verbose_name='扩展编号', primary_key=True)
username = models.CharField(verbose_name='用户名', max_length=30)
true_name = models.CharField(verbose_name='真实姓名', max_length=30)
sex = models.IntegerField(verbose_name='性别')
age = models.IntegerField(verbose_name='年龄', validators=[age_validator])
department = models.CharField(verbose_name='部门', max_length=20)
salary = models.DecimalField(verbose_name='薪水', max_digits=8, decimal_places=2)
status = models.CharField(verbose_name='状态', max_length=1, db_comment='1 有效, 0 无效')
create_date = models.DateField(verbose_name='创建日期', db_column='createDate', auto_now_add=True)
last_update_time = models.DateTimeField(verbose_name='最后更新时间', db_column='lastUpdateTime', auto_now=True)
memo = models.TextField(verbose_name='备注', blank=True, null=True)
user = models.OneToOneField(BaseUserInfo, on_delete=models.CASCADE)
depart = models.ForeignKey(DepartInfo, default="", on_delete=models.DO_NOTHING)
class Meta:
db_table = 'orm_user_extend_info'
db_table_comment = '人员扩展信息'
class SkillInfo(models.Model):
id = models.AutoField(verbose_name='技能编码', primary_key=True)
skill_name = models.CharField(verbose_name='特长', max_length=30)
create_date = models.DateField(verbose_name='创建时间', db_column='createDate', auto_now_add=True)
user = models.ManyToManyField(UserExtendInfo, db_table='orm_user_skill')
class Meta:
db_table = 'orm_skill_info'
db_table_comment = '技能信息'

@ -0,0 +1,36 @@
from orm_demo.models import *
# 插入数据
# 先实例化对象,然后为对象赋值
depart_data = DepartInfo()
depart_data.depart_name = '开发部'
depart_data.save()
# 实例化对象同时赋值
skill_data = SkillInfo(skill_name='PHP')
skill_data.save()
# create方法赋值
user = BaseUserInfo.objects.create(username='张三', password='zhangsan', status=1)
# create方式赋值, 字典格式数据
data = {'username': '李四', 'password': 'lisi', 'status': 1}
user = BaseUserInfo.objects.create(**data)
# 批量插入
data_list = [
{'username': '王五', 'password': 'wangwu', 'status': 1},
{'username': '孙六', 'password': 'sunliu', 'status': 1}
]
user_obj_list = []
for data in data_list:
user_obj = BaseUserInfo(username=data['username'], password=data['password'], status=data['status'])
user_obj_list.append(user_obj)
users = BaseUserInfo.objects.bulk_create(user_obj_list)
# 插入外键关联的数据
user1 = BaseUserInfo.objects.filter(username='张三').first()
department1 = DepartInfo.objects.filter(depart_name='开发部').first()
user_e1 = UserExtendInfo(username='张三', true_name='张三丰', sex=1, age=33, department='开发部', salary='230000.00',
status=1, memo='', user=user1, depart=department1)
user_e1.save()

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.
Loading…
Cancel
Save