1.项目构建
项目构建.png2.在Controller层进行设置路径
请求路径配置.png文章演示中,配置的是testdb的路径。
相对应的引入的testdb
3.处理模块
处理模块.png# -*- coding: utf-8 -*-
import json
from django.core import serializers
from django.http import HttpResponse
from TestModel.models import Rate
# 数据库操作
def testdb(request):
# 初始化
response = ""
response1 = ""
data = {}
# 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM
# list = Test.objects.all()
# filter相当于SQL中的WHERE,可设置条件过滤结果
response2 = Rate.objects.filter(region='陕西')
data['list'] = json.loads(serializers.serialize("json", response2))
print(data['list'])
# 获取单个对象
# response3 = Test.objects.get(id=1)
# 限制返回的数据 相当于 SQL 中的 OFFSET 0 LIMIT 2;
# Test.objects.order_by('name')[0:2]
#数据排序
# Test.objects.order_by("id")
# 上面的方法可以连锁使用
# Test.objects.filter(name="runoob").order_by("id")
# 输出所有数据
# for var in list:
# response1 += var.name + " "
# response = response1
return HttpResponse(data['list'])
4.数据库模型
对应数据库模型.pngfrom django.db import models
# 生育率的比较
class Rate(models.Model):
region = models.CharField(max_length=255, blank=True, null=True)
number_15_19岁 = models.CharField(db_column='15-19岁', max_length=255, blank=True, null=True) # Field renamed to remove unsuitable characters.
number_20_24岁 = models.CharField(db_column='20-24岁', max_length=255, blank=True, null=True) # Field renamed to remove unsuitable characters.
number_25_29岁 = models.CharField(db_column='25-29岁', max_length=255, blank=True, null=True) # Field renamed to remove unsuitable characters.
number_30_34岁 = models.CharField(db_column='30-34岁', max_length=255, blank=True, null=True) # Field renamed to remove unsuitable characters.
number_35_39岁 = models.CharField(db_column='35-39岁', max_length=255, blank=True, null=True) # Field renamed to remove unsuitable characters.
number_40_44岁 = models.CharField(db_column='40-44岁', max_length=255, blank=True, null=True) # Field renamed to remove unsuitable characters.
number_45_49岁 = models.CharField(db_column='45-49岁', max_length=255, blank=True, null=True) # Field renamed to remove unsuitable characters.
总和生育率 = models.CharField(max_length=255, blank=True, null=True)
class Rate2(models.Model):
region = models.CharField(max_length=255, blank=True, null=True)
其中,使用了命令 python manage.py inspectdb
得到原有数据表的结构
5.展示
数据库中的数据为:
数据.png
访问的结果为:
展示结果.png
网友评论