Commit 96719b55 authored by jackfrued's avatar jackfrued

更新了Django第三天代码

parent 9eaf6530
venv venv
.idea .idea
*.pyc *.pyc
__pycache__
# Generated by Django 2.0.5 on 2018-05-22 03:07
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Dept',
fields=[
('no', models.IntegerField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=20)),
('location', models.CharField(max_length=10)),
],
options={
'db_table': 'tb_dept',
},
),
migrations.CreateModel(
name='Emp',
fields=[
('no', models.IntegerField(primary_key=True, serialize=False)),
('name', models.CharField(max_length=20)),
('job', models.CharField(max_length=10)),
('mgr', models.IntegerField(null=True)),
('sal', models.DecimalField(decimal_places=2, max_digits=7)),
('comm', models.DecimalField(decimal_places=2, max_digits=7, null=True)),
('dept', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='hrs.Dept')),
],
options={
'db_table': 'tb_emp',
},
),
]
from django.db import models from django.db import models
# ORM - 对象关系映射
# 对象模型 <---> 关系模型
# 实体类 <---> 二维表
# 属性 <---> 列
# 对象 <---> 记录
class Dept(models.Model): class Dept(models.Model):
no = models.IntegerField(primary_key=True, verbose_name='部门编号') no = models.IntegerField(primary_key=True, verbose_name='部门编号')
name = models.CharField(max_length=20, verbose_name='部门名称') name = models.CharField(max_length=20, verbose_name='部门名称')
location = models.CharField(max_length=10, verbose_name='部门所在地') location = models.CharField(max_length=10, verbose_name='部门所在地')
excellent = models.BooleanField(default=0, verbose_name='是否优秀')
def __str__(self):
return self.name
class Meta: class Meta:
db_table = 'tb_dept' db_table = 'tb_dept'
......
from django.urls import path
from hrs import views
urlpatterns = [
path('depts', views.depts, name='depts'),
path('depts/emps', views.emps, name='empsindept'),
path('deldepts', views.del_dept, name='ddel')
]
from django.shortcuts import render from django.shortcuts import render, redirect
from django.urls import reverse
from hrs.models import Dept, Emp from hrs.models import Dept, Emp
...@@ -10,12 +11,26 @@ def index(request): ...@@ -10,12 +11,26 @@ def index(request):
return render(request, 'index.html', context=ctx) return render(request, 'index.html', context=ctx)
def del_dept(request):
# 重定向 - 重新请求一个指定的页面
return redirect(reverse('depts'))
def emps(request): def emps(request):
dno = int(request.GET['dno']) no = request.GET['no']
# dept = Dept.objects.get(no=no)
# ForeignKey(Dept, on_delete=models.PROTECT, related_name='emps')
# dept.emps.all()
# emps_list = dept.emp_set.all()
# all() / filter() ==> QuerySet
# QuerySet使用了惰性查询 - 如果不是非得取到数据那么不会发出SQL语句
# 这样做是为了节省服务器内存的开销 - 延迟加载 - 节省空间势必浪费时间
emps_list = list(Emp.objects.filter(dept__no=no).select_related('dept'))
ctx = {'emp_list': emps_list, 'dept_name': emps_list[0].dept.name} \
if len(emps_list) > 0 else {}
return render(request, 'emp.html', context=ctx)
def depts(request): def depts(request):
# DRY - Don't Repeat Yourself
# ORM - Object Relation Mapping
ctx = {'dept_list': Dept.objects.all()} ctx = {'dept_list': Dept.objects.all()}
return render(request, 'dept.html', context=ctx) return render(request, 'dept.html', context=ctx)
...@@ -126,3 +126,21 @@ USE_TZ = True ...@@ -126,3 +126,21 @@ USE_TZ = True
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
STATIC_URL = '/static/' STATIC_URL = '/static/'
# 配置将日志输出到控制台 日志级别为DEBUG(最详细的日志)
# DEBUG < INFO < WARNING < ERROR < CRITICAL
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),
},
},
}
...@@ -14,12 +14,12 @@ Including another URLconf ...@@ -14,12 +14,12 @@ Including another URLconf
2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
""" """
from django.contrib import admin from django.contrib import admin
from django.urls import path from django.urls import path, include
from hrs import views from hrs import views
urlpatterns = [ urlpatterns = [
path('', views.index), path('', views.index),
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('hrs/depts', views.depts) path('hrs/', include('hrs.urls')),
] ]
...@@ -22,6 +22,7 @@ ...@@ -22,6 +22,7 @@
<th>部门编号</th> <th>部门编号</th>
<th>部门名称</th> <th>部门名称</th>
<th>部门所在地</th> <th>部门所在地</th>
<th>是否优秀</th>
<th>操作</th> <th>操作</th>
</tr> </tr>
</thead> </thead>
...@@ -30,11 +31,19 @@ ...@@ -30,11 +31,19 @@
<tr> <tr>
<td>{{ dept.no }}</td> <td>{{ dept.no }}</td>
<td> <td>
<a href="/hrs/emps?dno={{ dept.no }}">{{ dept.name }}</a> <!-- 写代码时要尽量避免使用硬编码(hard code) -->
<a href="{% url 'empsindept' %}?no={{ dept.no }}">{{ dept.name }}</a>
</td> </td>
<td>{{ dept.location }}</td> <td>{{ dept.location }}</td>
<td> <td>
<a href="/hrs/deldept?dno={{ dept.no }}" class="btn btn-xs btn-warning">删除</a> {% if dept.excellent %}
<span style="color: green;"></span>
{% else %}
<span style="color: red;">×</span>
{% endif %}
</td>
<td>
<a href="{% url 'ddel' %}?dno={{ dept.no }}" class="btn btn-xs btn-warning">删除</a>
</td> </td>
</tr> </tr>
{% endfor %} {% endfor %}
......
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>员工</title>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<h3>{{ dept_name }}员工信息</h3>
<hr>
</div>
</div>
<div class="row clearfix">
<div class="col-md-8 column">
{% if emp_list %}
<table id="dept" class="table table-striped table-hover">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>职位</th>
<th>月薪</th>
<th>部门名称</th>
</tr>
</thead>
<tbody>
{% for emp in emp_list %}
<tr>
<td>{{ emp.no }}</td>
<td>{{ emp.name }}</td>
<td>{{ emp.job }}</td>
<td>{{ emp.sal }}</td>
<td>{{ dept_name }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<h2>此部门暂时没有员工!</h2>
{% endif %}
</div>
<div class="col-md-4 column">
</div>
</div>
<a href="{% url 'depts' %}">返回部门列表</a>
</div>
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script>
$(function() {
$('#dept tbody tr:even').addClass('info');
$('#dept tbody tr:odd').addClass('warning');
});
</script>
</body>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment