django笔记(三)模型以及增删查改
ORM对象关系模型
django自动将转换为sql语句,并返回结果
1.定义模型
Myapp目录下-models文件
from django.db import models
class Title(models.Model):
text=models.CharField(max_length=200)
create_date=models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.text
2激活模型
proc目录下setting.py文件添加
INSTALLED_APPS = [
# My apps
'myapp'
3.生成表
python manage.py makemigrations myapp
python manage.py migrate
4,增
myapp/forms.py,使用forms表单
from django import forms
from .models import Titles
class TopicForm(forms.ModelForm):
class Meta:
model=Titles
fields=['text']
labels={"text":""}
new_topic.html模板,使用form.as_p可以自动生成form
<form action="{% url 'myapp:new_topic' %}" method='post'>
{% csrf_token %}
{{ form.as_p }}
<button name="submit">Add topic</button>
</form>
视图
from .forms import TopicForm
def new_topic(request):
if request.method=='GET': #get请求时,返回表单
form=TopicForm()
else:
form=TopicForm(data=request.POST)
if form.is_valid():
form.save()
return redirect("myapp:titles")
content={'form':form}
return render(request,'myapp/new_topic.html',content)
路由
path('new_topic/',views.new_topic,name='new_topic'),
titles.html模板加上新增链接
<a href="{% url 'myapp:new_topic' %}">Add a new topic</a>
5.查询
给titles页面加个搜索的功能
<form action="{% url 'myapp:search'%}" method="get">
{% csrf_token %}
<input class='form-control form-control-sm' placeholder="请输入你要查找的关键字" type="text" name="key">
<!-- <input type="submit" value="搜索">-->
<button type="submit" class="btn btn-primary">搜索</button>
</form>
视图
def search(request):
request.encoding='utf-8'
titles = Titles.objects.filter(text__contains=request.GET['key']) #text字段包含,相当于where,用于模糊查找
context = {'titles': titles}
return render(request, 'myapp/titles.html', context)
其他
list = Titles.objects.all(),获取所有数据
firstdata=Titles.objects.get(id=1) #获取id=1的数据,id是主动生产的
firstdatas=Titles.objects.filter(id=1). order_by("create_date")
firstdatas=Titles.objects.filter(id=1). order_by("-create_date")#降序,减号表示降序
路由
re_path(r'^search/$', views.search,name='search')
image.png6.修改数据
模板,edit_topic.html
<h3>modify</h3>
<form action="{% url 'myapp:edit_topic' topic.id%}" method="post">
{% csrf_token %}
<p>topic: <input class='form-control form-control-sm' type="text" name="topic" value={{topic}}></p> #value为原有数据
<button type="submit" class="btn btn-primary">保存</button>
</form>
视图
def edit_topic(request,title_id): #修改没有使用form
titles = Titles.objects.get(id=title_id) #使用id查询出数据
topic={"topic":titles}
if request.method=='GET':
return render(request,'myapp/edit_topic.html',topic)
else:
newtopic=request.POST.get("topic") #获得请求中的topic新数据,更新
titles.text=newtopic
titles.save()
#return HttpResponse("<p>修改成功</p>")
return redirect(reverse('myapp:titles')) # 反向解析
url
path('edit_topic/<int:title_id>/',views.edit_topic,name='edit_topic'),
*给列表页加编辑连接
<a href="{% url 'myapp:edit_topic' title.id %}">Edit</a>
image.png7.删除
视图
def delete_topic(request,title_id):
titles = Titles.objects.get(id=title_id)
titles.delete() #使用delete直接删除对象实例
return redirect(reverse('myapp:titles')) # 反向解析,删除完返回到列表页
url
path('delete_topic/<int:title_id>/',views.delete_topic,name='delete_topic')
列表页加删除连接
<a href="{% url 'myapp:delete_topic' title.id %}">删除</a>
*点击删除后则直接删除了,可以考虑几个中间确认页面,
模板中删除连接先跳转到中间页面
<a href="{% url 'myapp:delete_confirm_topic' title.id %}">删除</a>
模板delete_confirm_topic.html
<h3>确认要删除吗?</h3>
<p>标题:{{title.text}}</p>
<p>创建时间:{{title.create_date}}</p>
<a class="nav-link" href="{% url 'myapp:titles'%}">取消</a>
<a href="{% url 'myapp:delete_topic' title.id %}">删除</a>
视图
def delete_confirm_topic(request,title_id):
titles = Titles.objects.get(id=title_id)
return render(request,'myapp/delete_confirm_topic.html',{"title":titles})
path('delete_confirm_topic/<int:title_id>/',views.delete_confirm_topic,name='delete_confirm_topic'),
点击删除后,先回跳到确认页面,点击删除,删除成功,点击取消,取消删除,返回列表页面
image.png