刚开始学习ORM

main
roger_home_pc 2 years ago
parent 39ae59dadb
commit e37685a8c0
  1. 40
      orm/db.py
  2. 22
      ormapp/manage.py
  3. 0
      ormapp/orm/__init__.py
  4. 3
      ormapp/orm/admin.py
  5. 6
      ormapp/orm/apps.py
  6. 61
      ormapp/orm/migrations/0001_initial.py
  7. 0
      ormapp/orm/migrations/__init__.py
  8. 54
      ormapp/orm/models.py
  9. 3
      ormapp/orm/tests.py
  10. 3
      ormapp/orm/views.py
  11. 0
      ormapp/ormapp/__init__.py
  12. 16
      ormapp/ormapp/asgi.py
  13. 140
      ormapp/ormapp/settings.py
  14. 22
      ormapp/ormapp/urls.py
  15. 16
      ormapp/ormapp/wsgi.py

@ -1,4 +1,12 @@
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):
@ -6,13 +14,41 @@ class BaseUserInfo(models.Model):
username = models.CharField(verbose_name='用户名', max_length=30)
password = models.CharField(verbose_name='密码', max_length=20)
status = models.CharField(verbose_name='状态', max_length=1)
createdate = models.DateField(verbose_name='创建日期', db_column='createDate')
createdate = models.DateField(verbose_name='创建日期', auto_now_add=True, db_column='createDate')
def __str__(self):
return self.id
return str(self.id) + '-' + self.username
class Meta:
managed = False
verbose_name = '人员基本信息'
db_table = 'UserBaseInfo'
class DepartInfo(models.Model):
id = models.AutoField(verbose_name='部门编号', primary_key=True)
departname = models.CharField(verbose_name='部门名称', max_length=30)
createdate = models.DateField(verbose_name='创建日期', db_column='createDate', auto_now_add=True)
class UserExtendInfo(models.Model):
id = models.AutoField(verbose='扩展编号', primary_key=True)
username = models.CharField(verbose_name='用户名', max_length=30)
turename = 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 无效')
createdate = models.DateField(verbose_name='创建日期', db_column='createDate', auto_now_add=True)
lastupdatetime = 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 SkillInfo(models.Model):
id = models.AutoField(verbose_name='技能编码', primary_key=True)
skillname = models.CharField(verbose_name='特长', max_length=30)
createdate = models.DateField(verbose_name='创建时间', db_column='createDate', auto_now_add=True)
user = models.ManyToManyField(UserExtendInfo, db_table='user_skill')

@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ormapp.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()

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

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

@ -0,0 +1,61 @@
# Generated by Django 4.2.3 on 2023-07-05 14:16
from django.db import migrations, models
import django.db.models.deletion
import orm.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='状态')),
('createdate', models.DateField(auto_now_add=True, db_column='createDate', verbose_name='创建日期')),
],
),
migrations.CreateModel(
name='DepartInfo',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, verbose_name='部门编号')),
('departname', models.CharField(max_length=30, verbose_name='部门名称')),
('createdate', models.DateField(auto_now_add=True, db_column='createDate', verbose_name='创建日期')),
],
),
migrations.CreateModel(
name='UserExtendInfo',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, verbose_name='扩展编号')),
('username', models.CharField(max_length=30, verbose_name='用户名')),
('turename', models.CharField(max_length=30, verbose_name='真实姓名')),
('sex', models.IntegerField(verbose_name='性别')),
('age', models.IntegerField(validators=[orm.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='状态')),
('createdate', models.DateField(auto_now_add=True, db_column='createDate', verbose_name='创建日期')),
('lastupdatetime', 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.departinfo')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='orm.baseuserinfo')),
],
),
migrations.CreateModel(
name='SkillInfo',
fields=[
('id', models.AutoField(primary_key=True, serialize=False, verbose_name='技能编码')),
('skillname', models.CharField(max_length=30, verbose_name='特长')),
('createdate', models.DateField(auto_now_add=True, db_column='createDate', verbose_name='创建时间')),
('user', models.ManyToManyField(db_table='user_skill', to='orm.userextendinfo')),
],
),
]

@ -0,0 +1,54 @@
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)
createdate = models.DateField(verbose_name='创建日期', auto_now_add=True, db_column='createDate')
def __str__(self):
return str(self.id) + '-' + self.username
# class Meta:
# managed = False
# verbose_name = '人员基本信息'
# db_table = 'UserBaseInfo'
class DepartInfo(models.Model):
id = models.AutoField(verbose_name='部门编号', primary_key=True)
departname = models.CharField(verbose_name='部门名称', max_length=30)
createdate = models.DateField(verbose_name='创建日期', db_column='createDate', auto_now_add=True)
class UserExtendInfo(models.Model):
id = models.AutoField(verbose_name='扩展编号', primary_key=True)
username = models.CharField(verbose_name='用户名', max_length=30)
turename = 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 无效')
createdate = models.DateField(verbose_name='创建日期', db_column='createDate', auto_now_add=True)
lastupdatetime = 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 SkillInfo(models.Model):
id = models.AutoField(verbose_name='技能编码', primary_key=True)
skillname = models.CharField(verbose_name='特长', max_length=30)
createdate = models.DateField(verbose_name='创建时间', db_column='createDate', auto_now_add=True)
user = models.ManyToManyField(UserExtendInfo, db_table='user_skill')

@ -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.

@ -0,0 +1,16 @@
"""
ASGI config for ormapp 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.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ormapp.settings')
application = get_asgi_application()

@ -0,0 +1,140 @@
"""
Django settings for ormapp project.
Generated by 'django-admin startproject' using Django 4.2.3.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""
import logging
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.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-y*29n6uy7o_w)$p1h&5p7^kce(6zzsuaradx_c8k_h&2ebzvc+'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'orm.apps.OrmConfig',
'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 = 'ormapp.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 = 'ormapp.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'django_w3cschool_demo',
'HOST': 'home.rogersun.cn',
'USER': 'root',
'PASSWORD': 'Sxzgx1209',
'PORT': '3306'
}
}
# Password validation
# https://docs.djangoproject.com/en/4.2/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.2/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.2/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
}
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level': 'DEBUG'
}
}
}

@ -0,0 +1,22 @@
"""
URL configuration for ormapp project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/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 ormapp 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.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ormapp.settings')
application = get_wsgi_application()
Loading…
Cancel
Save