CRM中QueryDict和模型表知识补充

1.QueryDict的用法

request.GET的用法:
1.在页面上输入:http://127.0.0.1:8000/index/
print(request.GET,type(request.GET))
<QueryDict: {}> <class 'django.http.request.QueryDict'>
在收到GET请求后,Django会将后面的参数以字典的形式接收。如果无参数就显示空字典
2.在页面上输入:http://127.0.0.1:8000/index/?page=2
<QueryDict: {'page': ['2']}> <class 'django.http.request.QueryDict'>
3.request.GET["name"]="jerd" #直接进行添加操作,操作失败
查看源码:
from django.http.request import QueryDict
class QueryDict(MultiValueDict):
_mutable = True
_encoding = None
def __init__(self, query_string=None, mutable=False, encoding=None):pass
在调用时,mutable=False,因此要向对request.GET接收的值及逆行更改。需要手动设置 _mutable = True
request.GET._mutable = True
request.GET["name"] = "jerd"
print(request.GET, type(request.GET))
<QueryDict: {'page': [''], 'name': ['jerd']}>
4.urlencode 将request.GET中的值拼接到一起,组成新的字符串
from django.http.request import QueryDict
request.GET._mutable = True
request.GET["name"] = "jerd"
print(request.GET.urlencode()) #page=&name=jerd 类型为字符串
5.deepcopy(request.GET)
在对GET来的数据处理时,一般都另复制一份进行操作,使用deepcopy
import copy
params=copy.deepcopy(request.GET)
params["name"]="zhao"
print(params) #<QueryDict: {'name': ['zhao']}>
为什么能直接添加了呢?
在request.GET中mutable默认为False,需要设置为True才能添加数据,而在拷贝的request.GET中却可以
直接添加,原因是在拷贝之后,mutable值为True
查看其源码:即不管是深拷贝还是浅拷贝,mutable值均为True
 def __copy__(self):
result = self.__class__('', mutable=True, encoding=self.encoding)
pass def __deepcopy__(self, memo):
result = self.__class__('', mutable=True, encoding=self.encoding)
memo[id(self)] = result
pass
print("params的mutable值为:",params._mutable) #params的mutable值为: True

2.ORM模型表知识补充

1.在models中创建模型表

class Book(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField( max_length=,verbose_name="书名")
publishDate=models.DateField(verbose_name="出版日期")
price=models.DecimalField(max_digits=,decimal_places=,verbose_name="价格")
publish=models.ForeignKey(to="Publish",to_field="nid",on_delete=models.CASCADE,verbose_name="出版社")
authors=models.ManyToManyField(to='Author',verbose_name="作者")
def __str__(self):
return self.title

2.根据模型表的类名取出app名和字符串类型的表名:

如在views中操作:

from app01 import models
app_name=models.Book._meta.app_label
model_name=models.Book._meta.model_name
print("app名字是:%s表名是%s"%(app_name,model_name))
app名字是:app02表名是food

3.通过字符串类型的字段名找到相应字段对象

Book类中的title,price,publish都是字段对象,max_length,verbose_name均是他们的属性
可直接调用,如title.max_length
通过"title"找到title对象:
obj = models.Book.model._meta.get_field("title")
print(obj.verbose_name) #书名

4.根据字段对象,找到其关联的表中的所有对象

related_data=publish.rel.to.objects.all()

3.Q查询补充

    from django.db.models import Avg,Count
from app01.models import Book
Book.objects.filter(title="go") #Out[]: <QuerySet [<Book: go>]>
#查询名称为go和价格为100的书籍
Book.objects.filter(title="go",price=) #Out[]: <QuerySet []>
##使用Q查询
from django.db.models import Q
查询题目为go,价格不是100的书籍
Book.objects.filter(Q(title="go")&~Q(price=)) #~非
<QuerySet [<Book: go>]>
Book.objects.filter(Q(title="go")&Q(price=))
Out[]: <QuerySet []>
Book.objects.filter(Q(title="go")|Q(price=))
Out[]: <QuerySet [<Book: go>]>
Q().children,通过字段字符串查询
q=Q()
##查询出title字段中值为go的对象
q.children.append(("title","go"))
Book.objects.filter(q)
Out[]: <QuerySet [<Book: go>]>
##查询出title字段中值含有g的对象
q.children.append(("title__contains","g"))
Book.objects.filter(q)
Out[]: <QuerySet [<Book: go>]>
q=Q() #不同的字段之间的关系默认为and
q.children.append(("title__contains","g"))
q.children.append(("price",))
Book.objects.filter(q)
Out[]: <QuerySet []>
q=Q()
q.connector="or" #不同的字段之间的关系更改为or
q.children.append(("title__contains","g"))
q.children.append(("price",))
Book.objects.filter(q)
Out[]: <QuerySet [<Book: go>]>

4.HTML中模板

1.{% include xxx.html %} 获取指定页面的所有内容
2. {% extends 'base.html' %} 当前HTML文件继承base.html
3.在模板中写上,{% block xxxx %}{% endblock %},在当前页面中可自义其中的内容
{% block page-css %}
pass
{% endblock %}
5.Xadmin页面的完整代码:
Xadmin/views.py
#根据ModelAdmin源码写
from django.conf.urls import url
from django.shortcuts import render,HttpResponse,redirect
from django.forms import ModelForm
from django.urls import reverse
from django.utils.safestring import mark_safe
from Xadmin.page import Pagination
from django.db.models import Q
class ShowList(object):
def __init__(self,config,data_list,request):
self.config=config #config是Modelxadmin的对象
self.data_list=data_list
self.request=request
##配置分页设置:
current_page = self.request.GET.get("page")
pagination = Pagination(current_page, self.data_list.count(), "%s" % self.config.get_list_url(), self.request.GET,
per_page_num=)
self.pagination=pagination
self.model_list = self.data_list[pagination.start:pagination.end]
#批量处理
self.actions=self.config.get_action()
self.list_filter=self.config.list_filter
#将函数名和描述值处理后在页面显示出来
def new_actions(self):
temp=[]
for action in self.actions:
temp.append({
"name":action.__name__,
"desc":action.short_description
})
return temp
def get_header(self):
# 处理表头 [check,'title', 'prcie',edit]
# .需要判断传的列表中的内容是函数名还是字符串
# .如果是字符串,判断是"__str__"还是其他的
head = []
# for field in self.list_display:
for field in self.config.new_list_display():
if isinstance(field, str):
if field == "__str__":
val = self.config.model._meta.model_name.upper() # 如果没定义样式类,表头就显示操作表的名字的大写
else:
# class Book(models.Model):
# title = models.CharField(max_length=, verbose_name="书名")
# price = models.DecimalField(max_digits=, decimal_places=, verbose_name="价格")
# 如果是字段字符串,让表头显示其定义的中文表头。title是字段对象,找到title后title.verbose_name 获取这个属性值
obj = self.config.model._meta.get_field(field)
val = obj.verbose_name
else:
val = field(self.config, is_header=True)
head.append(val)
return head
def get_body(self):
content = []
for obj in self.model_list:
temp = []
# for field in self.list_display:#自定义的样式类中有可能放的是自定义的函数名[check,'title', 'prcie',edit]
for field in self.config.new_list_display():
# 需要判断传的列表中的内容是函数名还是字符串
if isinstance(field, str): # 判断数据类型
# 处理多对多的字段方法二:判断是不是ManytoMany类型
from django.db.models.fields.related import ManyToManyField
try:
# 如果是__str__ 走到这会报错,因此使用抛出异常处理
many_obj = self.config.model._meta.get_field(field) # 取到字段对象
if isinstance(many_obj, ManyToManyField):
t = []
for i in getattr(obj, field).all():
t.append(i.name)
val = " | ".join(t)
else:
# val=getattr(obj,field) #相当于obj.title,obj.price 其中obj.__str__会自动触发这个方法
# 判断改字段是否在list_display_link,如果在,就设置成标签形式,不再就正常显示
if field in self.config.list_display_link:
edit_url = self.config.get_change_url(obj)
val = mark_safe("<a href='%s'>%s</a>" % (edit_url, getattr(obj, field)))
else:
val = getattr(obj, field)
except Exception as e:
val = getattr(obj, field)
else:
val = field(self.config, obj, ) # 定义的方法,obj为这个方法执行的哪条数据对象
temp.append(val)
content.append(temp)
return content # def get_page(self):
# # data_list = self.config.model.objects.all()
# current_page = self.request.GET.get("page")
# content=self.get_body()
# pagination = Pagination(current_page, self.data_list.count(), "%s" % self.config.get_list_url(), self.request.GET,
# per_page_num=)
# model_list = content[pagination.start:pagination.end]
# return pagination, model_list
def get_filter_link_tags(self):
# link_tags={"publish":["a","a"],"author":["a","a"]}
link_tags={}
from copy import deepcopy
for filter_field in self.list_filter:
# /Xadmin/app01/book/?page=
params = deepcopy(self.request.GET)#将后面的参数以字典的形式接收 {'page':}
current_id=self.request.GET.get(filter_field)
filter_field_obj=self.config.model._meta.get_field(filter_field)
#得到字段对象关联表的所有对象
related_data_list=filter_field_obj.rel.to.objects.all()
temp=[]
for obj in related_data_list:
params[filter_field]=obj.pk # {"authors":}
_url=params.urlencode()
# _url="%s=%s"%(filter_field,obj.pk)
if current_id==str(obj.pk):
s = "<a class='item' href='?%s'>%s</a>" % (_url, str(obj))
else:
s="<a href='?%s'>%s</a>"%(_url,str(obj))
temp.append(mark_safe(s))
link_tags[filter_field]=temp
return link_tags
class Modelxadmin(object):
model_form_class = None # 不设定的如果样式类中无model_form_class会报错
list_display_link = []
search_fields = []
actions=[]
list_filter = []
list_display=["__str__"] #设置Modelxadmin的静态属性,即当注册的对象没使用样式类时,使用Modelxadmin的样式属性
def __init__(self,model,site): #如果传的是book,model就是Book 传的是publish,model就是Publiah
self.model=model
self.site=site
self.model_name = self.model._meta.model_name
self.app_name = model._meta.app_label # 定义ModelForm组件。 由于每张表中的字段都不同,Modelxadmin的ModelForm组件不能显示错误信息
#如果要显示出错误信息,就在自己样式类中自当义ModelForm组件
def get_model_form_class(self):
if self.model_form_class:
print()
return self.model_form_class #得到自定义BookModelForm类
else:
#自定义类中没设置MOdelform的将model_form_class=None
from django.forms import ModelForm
class DemoModelForm(ModelForm):
class Meta:
model=self.model
fields="__all__"
return DemoModelForm
##反向解析得到路径,如果在函数中使用 list_url="%s/%s/"%(self.app_name,self.model_name)
##相当于是在当前路径后拼接,会报错
def get_add_url(self):
url_name="{}/{}_add".format( self.app_name, self.model_name)
_url=reverse(url_name)
return _url
def get_list_url(self):
url_name = "{}/{}_list".format(self.app_name, self.model_name)
_url = reverse(url_name)
return _url
def get_change_url(self,obj):
url_name = "{}/{}_change".format(self.app_name, self.model_name)
_url = reverse(url_name,args=(obj.pk,))
return _url
def get_del_url(self,obj):
url_name = "{}/{}_del".format(self.app_name, self.model_name)
_url = reverse(url_name,args=(obj.pk,))
return _url
# 选择按钮 编辑 删除
def edit(self, obj=None, is_header=False):
if is_header: # 此时作表头处理
return "操作"
else:
v=self.get_change_url(obj)
return mark_safe("<a href='%s'>编辑</a>" %v)
def delete(self, obj=None, is_header=False):
if is_header: # 此时作表头处理
return "操作"
v = self.get_del_url(obj)
return mark_safe("<a href='%s'>删除</a>" %v)
def check(self, obj=None, is_header=False):
if is_header: # 此时作表头处理
return "选择"
return mark_safe("<input type='checkbox' name='selected' value='%s'>"%obj.pk)
#构建新的list_dispaly
def new_list_display(self):
temp=[]
temp.append(Modelxadmin.check)
temp.extend(self.list_display)
#判断是否加编辑操作
if not self.list_display_link:
temp.append(Modelxadmin.edit)
temp.append(Modelxadmin.delete)
return temp
##搜索
def get_search(self,request):
search_condition=Q()
search_condition.connector='or'
search_value = request.GET.get("search_value")
if search_value:
for search_field in self.search_fields:
search_condition.children.append((search_field+"__icontains", search_value)) #元祖
return search_condition
##批处理:得到注册对象样式类中指定的操作,并为所有的注册对象添加上删除操作
def all_delete(self,request,queryset):
queryset.delete()
list_url=self.get_list_url()
return redirect("%s"%list_url)
all_delete.short_description="批量删除"
def get_action(self): #将批量删除和样式类中的actions合到一起
temp=[]
temp.append(self.all_delete)
temp.extend(self.actions) #迭代添加
return temp #将得到的temp作为ShowList的一个属性
def list_view(self, request): #self是Modelxadmin的实例对象,要么是自定义样式类的实例对象
type=request.GET.get("name")
if not type:type=""
if request.method=='POST': #批量操作
action=request.POST.get("action") #哪种操作
print("操作是",action)
selected_pk=request.POST.getlist("selected") #操作的数据
action_obj=self.model.objects.filter(pk__in=selected_pk)
action=getattr(self,action)
ret=action(request,action_obj)
return ret
#print(self.model) #用户调用的哪张表,self.model就是哪张表 <class 'app02.models.Order'>
search_condition=self.get_search(request)
##过滤查询:
filter_condition=Q()
for filter_field,val in request.GET.items():
##当选择分页时,页面上会把page=2传过来,仍走这一步,但是表中并没有这个字段,所以会报错
if filter_field not in ['page',"search_value"]:
filter_condition.children.append((filter_field,val))
data_list = self.model.objects.filter(filter_condition).filter(search_condition) #search_condition有值,就按值搜索,无值就搜索全部
#data_list = self.model.objects.all() # 取出每一条数据的对象,data_list[].字段名(title) 就能得到相应的数据
show_list=ShowList(self,data_list,request) #self是 Modelxadmin的实例对象 # 获取增加页面的url 点击增加的时候,跳到增加页面。自动拼接add_url="add"
return render(request,"list.html",{"show_list":show_list,"add_url":self.get_add_url()})
def add_view(self, request):
# list_url="%s/%s/"%(self.app_name,self.model_name)
DemoModelForm=self.get_model_form_class() #得到定义的ModelForm组件类
if request.method=='POST':
form_obj=DemoModelForm(request.POST)
if form_obj.is_valid():
form_obj.save()
# return redirect(list_url) #不能用,相当于在当前路径后面拼接
return redirect(self.get_list_url())
else:
return render(request,'add_view.html',locals())
form_obj = DemoModelForm()
return render(request, 'add_view.html', locals())
def change_view(self, request, id):
DemoModelForm = self.get_model_form_class() # 得到定义的ModelForm组件类
change_obj=self.model.objects.get(pk=id)
if request.method == 'POST':
form_obj = DemoModelForm(request.POST,instance=change_obj)
if form_obj.is_valid():
form_obj.save()
# return redirect(list_url) #不能用,相当于在当前路径后面拼接
return redirect(self.get_list_url())
else:
return render(request, 'change_view.html', locals())
form_obj = DemoModelForm(instance=change_obj)
return render(request, 'change_view.html', locals())
def del_view(self, request, id):
if request.method=='POST':
self.model.objects.get(pk=id).delete()
return redirect(self.get_list_url())
return render(request,"del_view.html",{"url":self.get_list_url()}) def get_url_2(self):
temp = []
# print("=====",model_name )
# temp.append(url(r"^$", self.list_view))
temp.append(url(r"^$", self.list_view,name="{}/{}_list".format( self.app_name, self.model_name)))
temp.append(url(r"^add/$", self.add_view,name="{}/{}_add".format( self.app_name, self.model_name)))
# temp.append(url(r"^(\d+)/change/$", self.change_view,))
temp.append(url(r"^change/(\d+)/$", self.change_view,name="{}/{}_change".format( self.app_name, self.model_name) ))
temp.append(url(r"^del/(\d+)/$", self.del_view,name="{}/{}_del".format( self.app_name, self.model_name)))
return temp
@property
def urls2(self):
return self.get_url_2(), None, None class XadminSite(object):
def __init__(self, name='admin'):
self._registry = {}
def register(self, model, admin_class=None, **options):
if not admin_class:
admin_class = Modelxadmin #根据AdminSite源码,定义夜歌admin_class类
self._registry[model] = admin_class(model, self) # {Book:ModelAdmin(Book)} self.model=Book
def get_urls(self):
temp = []
print(self._registry)
for model, xadmin_class in self._registry.items(): #xadmin_class=admin_class(model, self)是注册的模型表对象 ModelAdmin(Book)
app_name = model._meta.app_label # 拿到app的名字
model_name = model._meta.model_name # 拿到字符串类型的表名
print("表名是:",model_name)
temp.append(url(r"^{}/{}/".format(app_name, model_name), xadmin_class.urls2,))
'''
url(r"app01/book",ModelXadmin(Book,site).urls2)
url(r"app01/publish",ModelXadmin(Publish,site).urls2)
url(r"app02/order",ModelXadmin(Order,site).urls2) '''
return temp @property
def urls(self): #self就是XadminSite单例出来的对象
return self.get_urls(), None, None
site=XadminSite() #生成单例对象

app01/xadmin.py

print("Xadmin app01")
from Xadmin.service.Xadmin import site,Modelxadmin
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
from django.utils.safestring import mark_safe
from django.urls import reverse
from django.forms import ModelForm
from django.forms import widgets as wid #因为重名,所以起个别名
class BookModelForm(ModelForm):
class Meta:
model=models.Book
fields="__all__"
error_messages={
"title":{"required":"该字段不能为空!"}
}
widgets = {
" publishDate": wid.TextInput(attrs={"type": "date"})
}
##将操作封装到类中
'''
class Operation():
def edit(self, obj,is_header):
if is_header: # 此时作表头处理
return "操作"
else:
url_name = "{}/{}_change".format(self.app_name, self.model_name) # BookConfig中没有self.app_name,就去Modelxadmin找
v = reverse(url_name, args=(obj.pk,))
return mark_safe("<a href='%s'>编辑</a>" % v)
def delete(self, obj, is_header):
if is_header: # 此时作表头处理
return "操作"
return mark_safe("<a href='del/%s/'>删除</a>" % obj.pk) def check(self, obj, is_header):
if is_header: # 此时作表头处理
return "选择"
else:print()
return mark_safe("<input type='checkbox'>")
'''
class BookConfig(Modelxadmin):
#自定义方法,obj默认为None,即在处理表头时用不到,is_header默认为False,在处理表头时用得到,处理表单内容时用不到
#href='%s/change/'自动拼接路径
##在每个对象中添加删除,编辑,选择按钮
'''
def edit(self, obj=None, is_header=False):
if is_header: # 此时作表头处理
return "操作"
##反向解析url
url_name="{}/{}_change".format( self.app_name, self.model_name) #BookConfig中没有self.app_name,就去Modelxadmin找
v = reverse(url_name, args=(obj.pk,))
return mark_safe("<a href='%s'>编辑</a>" % v)
#自动拼接路由
# return mark_safe("<a href='change/%s/'>编辑</a>"%obj.pk) def delete(self, obj=None, is_header=False):
if is_header: # 此时作表头处理
return "删除"
return mark_safe("<a href='del/%s/'>删除</a>" % obj.pk) def check(self, obj=None, is_header=False):
if is_header: # 此时作表头处理
return "选择"
return mark_safe("<input type='checkbox'>")
'''
##处理多对多的字段方法一:
'''
def display_authors(self,obj=None, is_header=False):
if is_header:
return "作者名称"
s=[]
for author in obj.authors.all(): #必须使用all(),得到所有的作者对象
s.append(author.name) #取出每个作者对象的name属性
val=" | ".join(s)
return mark_safe(val) list_display = [check, "title", "price", "publish", display_authors, edit, delete]
'''
###将编辑,删除,批量操作封装到一个类中,但是需要在每个样式类中给设定
'''
def check(self,obj=None, is_header=False):return super().check(obj, is_header)
def edit(self,obj=None, is_header=False):return super().edit(obj, is_header)
def delete(self,obj=None, is_header=False):return super().delete(obj, is_header)
list_display=[check,"title","price","publish","authors",edit,delete] '''
model_form_class = BookModelForm
list_display = ["title", "price", "publish", "authors"]
list_display_link=["title"]
search_fields = ["title", "price"]
#批量处理
def all_update(self,request,queryset): #queryset为数据对象
queryset.update(price=)
list_url = self.get_list_url()
return redirect("%s" % list_url)
all_update.short_description="批量初始化"
actions=[all_update,]
#设置过滤:
list_filter=["publish","authors"] site.register(models.Book,BookConfig)
class PublishConfig(Modelxadmin):
list_display=["name","city","email"]
site.register(models.Publish,PublishConfig)
class AuthorConfig(Modelxadmin):
list_display=["name","age"]
site.register(models.Author,AuthorConfig) site.register(models.AuthorDetail)
app02/xadmin.py
print("Xadmin app02")
from Xadmin.service.Xadmin import site
from Xadmin.service.Xadmin import Modelxadmin
from app02 import models
class OrderConfig(Modelxadmin):
list_display=["title","addr"]
site.register(models.Order)
# class FoodConfig(Modelxadmin):
# list_display=["title","price"]
site.register(models.Food)
print(site._registry)
list.HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
<link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/dashboard.css" rel="stylesheet">
<style>
.item{
background-color: #985f0d;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3 col-md-2 sidebar">
<ul class="nav nav-sidebar">
<li class="display active"><a href="/Xadmin/app01/book/ ">图书列表页<span class="sr-only">(current)</span></a>
</li>
<li class="display active"><a href="/Xadmin/app01/publish/">出版社列表页</a></li>
<li class="display active"><a href="/Xadmin/app01/author/">作者列表页</a></li>
<li class="display active"><a href="/Xadmin/app02/order/">订单列表页</a></li>
<li class="display active"><a href="/Xadmin/app02/food/">美食列表页</a></li>
</ul> </div>
<div class="col-sm-7 col-sm-offset-3 col-md-7 col-md-offset-2 main">
<h1 class="page-header" STYLE="color: #dff0d8">管理</h1> <div class="panel panel-success">
<!-- Default panel contents -->
<div class="panel-heading">信息 <i class="fa fa-thumb-tack pull-right"></i></div>
<div class="panel-body">
<div class="row" style="margin-bottom: 15px">
<div class="col-md-4">
{% if show_list.config.search_fields %}
<div class="input-group">
<form action="" method="get"> <span class="input-group-btn">
<input type="text" name="search_value" class="form-control" placeholder="Search for..." style="display: inline-block">
<button class="btn btn-default" >搜索</button>
</span>
</form>
</div><!-- /input-group -->
{% endif %} </div><!-- /.col-md- -->
<div class="col-md-1 pull-right">
<a class="btn btn-success" href="{{ add_url }}">新增</a>
</div>
</div><!-- /.row -->
<div class="row" style="margin-bottom: 15px">
<form action="" method="post">
{% csrf_token %}
<div class="col-md-3" style="margin-bottom: 15px">
<div class="input-group">
<span class="input-group-btn" >
<select name="action" id="" class="form-control">
<option value="">------------------</option>
{% for foo in show_list.new_actions %}
<option value="{{ foo.name }}">{{foo.desc }}</option>
{% endfor %}
</select>
<button class="btn btn-default" >GO</button>
</span>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>序号</th>
{% for foo in show_list.get_header %}
<th>{{ foo }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for foo in show_list.get_body %}
<tr>
<td>{{ forloop.counter }}</td>
{% for foo1 in foo %}
<td>{{ foo1 }}</td>
{% endfor %} </tr>
{% endfor %}
</tbody>
</table> </form>
</div>
<ul class="pull-right">
{{show_list.pagination.page_html|safe }}
</ul> </div> </div> </div>
<div class="col-sm-2">
{% for filter_filed,link_tag_list in show_list.get_filter_link_tags.items %}
<p>By {{ filter_filed.upper }}</p>
{% for link_tag in link_tag_list %}
<p>{{ link_tag }}</p>
{% endfor %}
{% endfor %} </div>
</div>
</div> <script src="/static/jquery-3.3.1.js"></script>
<script src="/static/bootstrap/js/bootstrap.min.js"></script> {#未使用样式#} {#[{'title': '江南', 'addr': '北京'}, {'title': '醉赤壁', 'addr': '上海'}, {'title': '杀手', 'addr': '广州'}]#}
{#<p>#}
{# <span>序号</span>#}
{# {% for foo in head %}#}
{# <span>{{ foo }}</span>#}
{# {% endfor %}#}
{#</p>#}
{##}
{#{% for foo in content %}#}
{# <P>#}
{# <span>{{ forloop.counter }}</span>#}
{# {% for foo1 in foo %}#}
{# <span>{{ foo1 }}</span>#}
{# {% endfor %}#}
{# </P>#}
{#{% endfor %}#} </body>
</html>

models.py

from django.db import models

# Create your models here.
class Author(models.Model):
nid = models.AutoField(primary_key=True)
name=models.CharField( max_length=,verbose_name="作者")
age=models.IntegerField(verbose_name="年龄")
# 与AuthorDetail建立一对一的关系
authorDetail=models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE)
def __str__(self):
return self.name
class AuthorDetail(models.Model):
nid = models.AutoField(primary_key=True)
birthday=models.DateField()
telephone=models.BigIntegerField(verbose_name="手机号")
addr=models.CharField( max_length=,default="北京",verbose_name="地址")
def __str__(self):
return self.birthday
class Publish(models.Model):
nid = models.AutoField(primary_key=True)
name=models.CharField( max_length=,verbose_name="出版社")
city=models.CharField( max_length=,verbose_name="地址")
email=models.EmailField()
def __str__(self):
return self.name class Book(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField( max_length=,verbose_name="书名")
publishDate=models.DateField(verbose_name="出版日期")
price=models.DecimalField(max_digits=,decimal_places=,verbose_name="价格")
def __str__(self):
return self.title # 与Publish建立一对多的关系,外键字段建立在多的一方
publish=models.ForeignKey(to="Publish",to_field="nid",on_delete=models.CASCADE,verbose_name="出版社")
# 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表
authors=models.ManyToManyField(to='Author',verbose_name="作者") def __str__(self):
return self.title
 
04-15 16:20