多对多表的三种创建方式
1.全自动创建----ManyToManyField
class Book(models.Model):
title = models.CharField(max_length=32)
authors = models.ManyToManyField(to='Author')
class Author(models.Model):
name = models.CharField(max_length=32)
优势:自动创建第三张表 并可以这个表进行 add remove set clear四种操作
劣势:第三张表无法创建更多的字段 扩展性较差
2.纯手动创建
class Book(models.Model):
title = models.CharField(max_length=32)
class Author(models.Model):
name = models.CharField(max_length=32)
class Book2Author(models.Model):
book = models.ForeignKey(to='Book')
author = models.ForeignKey(to='Author')
others = models.CharField(max_length=32)
join_time = models.DateField(auto_now_add=True)
第三张表的外键分别是2个 关联的表格
优势:第三张表完全自己创建 扩展性抢
劣势:编写繁杂 并不再支持add remove set clear四种操作 和 正反向查询方式
3.半自动创建
class Book(models.Model):
title = models.CharField(max_length=32)
authors = models.ManyToManyField(to='Author', through='Book2Author', through_fields=('book','author')
# 在ManyToManyField中 关联表 through=第三张表名 through_fields('book','author')
# 关联的第三张表字段
class Author(models.Model):
name = models.CharField(max_length=32)
class Book2Author(models.Model):
book = models.ForeignKey(to='Book', on_delete=models.CASCADE)
author = models.ForeignKey(to='Author', on_delete=models.CASCADE)
others = models.CharField(max_length=32)
join_time = models.DateField(auto_now_add=True)
优势:第三张表完全由自己创建 扩展性强 正反向概念依然清晰可用
劣势:编写繁琐不再支持add、remove、set、clear
django内置序列化组建(drf)前身
'''前后端分离的项目 视图函数只需要返回json格式的数据即可'''
from app01 import models
from django.http import JsonResponse
def ab_ser_func(request):
# 1.查询所有的书籍对象
book_queryset = models.Book.objects.all() # queryset [对象、对象]
# 2.封装成大字典返回
data_dict = {}
for book_obj in book_queryset:
temp_dict = {}
temp_dict['pk'] = book_obj.pk
temp_dict['title'] = book_obj.title
temp_dict['price'] = book_obj.price
temp_dict['info'] = book_obj.info
data_dict[book_obj.pk] = temp_dict # {1:{},2:{},3:{},4:{}}
return JsonResponse(data_dict)
普通写法
from django.core import serializers
导入内置模块
res = serializers.serialize('json', book_queryset)
# 直接把从数据库拿到的queryset 直接发送即可 模块会帮你转化为json格式
return HttpResponse(res)
前端就会直接接收到数据为 json格式的
批量插入数据
如果要批量对某个表插入数据
使用关键词 bulk_create 批量创建
bulk_update 批量更新
book_list = []
for i in range(10000):
book_obj = models.Book(name='第%s本书'%i)
book_list.append(book_obj)
# 先创建所有对象 并汇集到一个列表 这时候还没有对数据库进行操作
models.Book.objects.bulk_create(book_list)
# 直接把所有对象列表放入bulk_create中即可
自定义分页器使用
当我们需要使用非django内置的第三方组建或代码时
统一在项目根目录下创建一个 utils文件夹 用于存放
class Pagination(object):
def __init__(self, current_page, all_count, per_page_num=2, pager_count=11):
"""
封装分页相关数据
:param current_page: 当前页
:param all_count: 数据库中的数据总条数
:param per_page_num: 每页显示的数据条数
:param pager_count: 最多显示的页码个数
"""
try:
current_page = int(current_page)
except Exception as e:
current_page = 1
if current_page < 1:
current_page = 1
self.current_page = current_page
self.all_count = all_count
self.per_page_num = per_page_num
# 总页码
all_pager, tmp = divmod(all_count, per_page_num)
if tmp:
all_pager += 1
self.all_pager = all_pager
self.pager_count = pager_count
self.pager_count_half = int((pager_count - 1) / 2)
@property
def start(self):
return (self.current_page - 1) * self.per_page_num
@property
def end(self):
return self.current_page * self.per_page_num
def page_html(self):
# 如果总页码 < 11个:
if self.all_pager <= self.pager_count:
pager_start = 1
pager_end = self.all_pager + 1
# 总页码 > 11
else:
# 当前页如果<=页面上最多显示11/2个页码
if self.current_page <= self.pager_count_half:
pager_start = 1
pager_end = self.pager_count + 1
# 当前页大于5
else:
# 页码翻到最后
if (self.current_page + self.pager_count_half) > self.all_pager:
pager_end = self.all_pager + 1
pager_start = self.all_pager - self.pager_count + 1
else:
pager_start = self.current_page - self.pager_count_half
pager_end = self.current_page + self.pager_count_half + 1
page_html_list = []
# 添加前面的nav和ul标签
page_html_list.append('''
<nav aria-label='Page navigation>'
<ul class='pagination'>
''')
first_page = '<li><a href="?page=%s">首页</a></li>' % (1)
page_html_list.append(first_page)
if self.current_page <= 1:
prev_page = '<li class="disabled"><a href="#">上一页</a></li>'
else:
prev_page = '<li><a href="?page=%s">上一页</a></li>' % (self.current_page - 1,)
page_html_list.append(prev_page)
for i in range(pager_start, pager_end):
if i == self.current_page:
temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,)
else:
temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,)
page_html_list.append(temp)
if self.current_page >= self.all_pager:
next_page = '<li class="disabled"><a href="#">下一页</a></li>'
else:
next_page = '<li><a href="?page=%s">下一页</a></li>' % (self.current_page + 1,)
page_html_list.append(next_page)
last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,)
page_html_list.append(last_page)
# 尾部添加标签
page_html_list.append('''
</nav>
</ul>
''')
return ''.join(page_html_list)
后端代码
from utils.mypage import Pagination
def book_list(request):
book_obj_list = models.Book.objects.all()
all_count = book_obj_list.count()
current_page = request.GET.get('page',1)
page_obj = Pagination(current_page=current_page,all_count=all_count)
# 实例化传值生成对象
page_obj_list = book_obj_list[page_obj.start:page_obj.end]
# 对总数据进行切片处理
return render(request, 'book_list.html', locals())
前端代码
<div class="text-center">
{{ page_obj.page_html|safe }}
</div>
标签:自定义,批量,models,self,current,book,pager,page,分页
From: https://www.cnblogs.com/moongodnnn/p/16995049.html