Django_Model.整理

本文详细介绍了使用Django ORM进行数据库表设计的过程,包括字段定义、表关系、数据限制及表方法等内容,旨在帮助开发者掌握高效的数据存储与管理技巧。

Model表设计

数据定义数据存储,输出
a.定义表(信息 =字段) + 定义表关系 + (定义/限制)数据
b.通过orm等方法来,定义method来编辑原始数量来输出
__str__

1.表设计

数据库表的属性
主键
unique_key
默认值(default)
null/blank
max_length

django admin的属性
verbose_name
help_text

2.表关系

foreignkey
on_delete
manytomany

3.字段的数据限制(定义)
choice
数据值的方法(数据库表里查询)

4.表的方法
1.必须写
__str__

2.字段的文字方法(简单)
def show_classes(self):
return ' | '.join([str(i) for i in self.class_list.all()])

3.字段的文字方法(对象)

def show_status(self):
"""
"""

color_dict = {
"signed": "green",
"unregistered": "red",
"studying": "pink",
"paid_in_full": "blue"
}

return mark_safe(
'<span style= "background-color: {};color: white; padding: 4px">{}</span>'.format(color_dict[self.status],
self.get_status_display()))

def show_classes(self):
return ' | '.join([str(i) for i in self.class_list.all()])

def enroll_link(self):

if not self.enrollment_set.exists():
return mark_safe('<a href={}">添加报名表</a>'.format(reverse('add_enrollment', args=(self.id,))))
else:
return mark_safe(
'<a href={}">添加</a> | <a href={}">查看</a>'.format(reverse('add_enrollment', args=(self.id,)),
reverse('enrollment', args=(self.id,))))

def __str__(self):
return self.name

5.表的meta
index
unique_together

ModelForm
1.表设计

数据库表的属性
主键
unique_key
默认值(default)
null/blank
max_length

django admin的属性
verbose_name
help_text

2.表关系

foreignkey
on_delete
to 
related_name
manytomany


3.字段的数据限制(定义)
choice
数据值的方法

4.表的方法
__str__

5.拿到数据的值的方法


5.表的meta
index
unique_together

from django.http import HttpRequest, HttpResponse,JsonResponse from django.shortcuts import render # 加载model from gaode.models import T_info # JsonResponse # Create your views here. from django.views.decorators.csrf import csrf_exempt def index(request): return render(request, 'index.html') # 增加数据api @csrf_exempt def add_data(request): print(request.POST) # 获取前端传递的数据 city = request.POST.get('city') name = request.POST.get('name') lat = request.POST.get('lat') lng = request.POST.get('lng') desc = request.POST.get('desc') # 创建model对象 t_info = T_info() # 将前端传递的数据赋值给model对象 t_info.city = city t_info.name = name t_info.lat = lat t_info.lng = lng t_info.desc = desc t_info.save() return JsonResponse({'code': 0, 'msg': 'success'}) # 查询 @csrf_exempt def query_data(request): # 判断是否有查询条件 if request.GET.get('id'): print(request.GET.get('id')) # 根据id查询数据 t_info = T_info.objects.get(id=request.GET.get('id')) # 返回数据 return JsonResponse({'code': 0, 'msg': 'success', 'data': { 'id': t_info.id, 'city': t_info.city, 'name': t_info.name, 'lat': t_info.lat, 'lng': t_info.lng, 'desc': t_info.desc }}) else: # 查询数据 t_info_list = T_info.objects.all() # 将查询结果转换为json t_info_list_json = [] for t_info in t_info_list: t_info_list_json.append({ 'id': t_info.id, 'city': t_info.city, 'name': t_info.name, 'lat': t_info.lat, 'lng': t_info.lng, 'desc': t_info.desc }) return JsonResponse({'code': 0, 'msg': 'success', 'data': t_info_list_json}) # 删除 def delete_data(request): # 获取前端传递的id id = request.GET.get('id') # 根据id删除数据 T_info.objects.filter(id=id).delete() return JsonResponse({'code': 0, 'msg': 'success'}) # 更新 @csrf_exempt def update_data(request): # 获取前端传递的数据 id = request.POST.get('id') city = request.POST.get('city') name = request.POST.get('name') lat = request.POST.get('lat') lng = request.POST.get('lng') desc = request.POST.get('desc') # 根据id查询数据 t_info = T_info.objects.get(id=id) # 将前端传递的数据赋值给model对象 t_info.city = city t_info.name = name t_info.lat = lat t_info.lng = lng t_info.desc = desc t_info.save() return JsonResponse({'code': 0, 'msg': 'success'}) @csrf_exempt def get_data(request): #遍历url中的参数 print(11) for k,v in request.GET.items(): print(k,v) # 查询 if(k=='city'): # 模糊查询 t_info_list = T_info.objects.filter(city__contains=v) elif(k=='name'): t_info_list = T_info.objects.filter(name__contains=v) # t_info_list = T_info.objects.filter(k=v) # 将查询结果转换为json t_info_list_json = [] for t_info in t_info_list: t_info_list_json.append({ 'id': t_info.id, 'city': t_info.city, 'name': t_info.name, 'lat': t_info.lat, 'lng': t_info.lng, 'desc': t_info.desc }) return JsonResponse({'code': 0, 'msg': 'success', 'data': t_info_list_json})需要导入什么库
最新发布
06-18
python manage.py createsuperuser Traceback (most recent call last): File "E:\learn\ttsxzjc\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\__init__.py", line 16, in setup from django.urls import set_script_prefix File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\urls\__init__.py", line 1, in <module> from .base import ( File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\urls\base.py", line 8, in <module> from .exceptions import NoReverseMatch, Resolver404 File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\urls\exceptions.py", line 1, in <module> from django.http import Http404 File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\http\__init__.py", line 5, in <module> from django.http.response import ( File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\http\response.py", line 13, in <module> from django.core.serializers.json import DjangoJSONEncoder File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\core\serializers\__init__.py", line 23, in <module> from django.core.serializers.base import SerializerDoesNotExist File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\core\serializers\base.py", line 6, in <module> from django.db import models File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\db\models\__init__.py", line 3, in <module> from django.db.models.aggregates import * # NOQA ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\db\models\aggregates.py", line 5, in <module> from django.db.models.expressions import Case, Func, Star, When File "E:\learn\ttsxzjc\.venv\Lib\site-packages\djan
03-25
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值