django进阶
Posted 人生苦短,我用python
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django进阶相关的知识,希望对你有一定的参考价值。
django ORM操作
models.py
from django.db import models # Create your models here. class Book(models.Model): name = models.CharField(max_length=128) price = models.PositiveSmallIntegerField(null=True)#正数,null=True不是必填 authors = models.ManyToManyField(‘Author‘) publisher = models.ForeignKey(‘Publisher‘) pub_date = models.DateField() # memo = models.CharField(null=True,max_length=64)数据库新增字段的时候,需要加上null=True #为了在查询时显示对象的名字 def __str__(self): return self.name class Author(models.Model): name = models.CharField(max_length=32) email = models.EmailField(unique=True) def __str__(self): return self.name class Publisher(models.Model): name = models.CharField(max_length=128,unique=True) website = models.URLField(unique=True) def __str__(self): return "%s %s"%(self.name,self.website)
terminal下进行数据库的增删改查
python3 manage.py shell
from app01 import models
book表增加数据,关联author和publisher表,所以先创建author和publisher,创建时不能直接指定author
models.Author.objects.create(name=‘alex‘,email=‘[email protected]‘) models.Publisher.objects.create(name=‘tsinghua‘,website=‘http://tsinghua.com)
b2 = models.Book.objects.create(name=‘linux‘,price=55,publisher_id=2,pub_date=‘2016-01-01‘)
b2.authors.add(1,2)
b2.authors.all()#查询这本书的作者,创建完之后是保存在app01_book_authors表中
b2.authors.remove()
b2.publiser.name#查看外键关键的表的属性
查
返回列表 models.Book.objects.fliter()
返回单个对象或错误,如果get到多条会报错 models.Book.objects.get()
models.Book.objects.get(pub_date__gt = ‘2017-01-01‘)
查询没有就创建
models.Book.objects.get_or_create(name=‘java‘,pub_date=‘2019-01-01‘,publisher_id=1)
(<Book: java>, True)
包含(contains,incontains忽略大小写)
models.Book.objects.filter(name__contains=‘go‘)
<QuerySet [<Book: go>]>
查name和price
models.Book.objects.values(‘name‘,‘price‘)
<QuerySet [{‘name‘: ‘python‘, ‘price‘: 50}, {‘name‘: ‘linux‘, ‘price‘: 55}, {‘name‘: ‘go‘, ‘price‘: 100}, {‘name‘: ‘java‘, ‘price‘: None}]>
查价格不等于50的book
models.Book.objects.exclude(price=50)
<QuerySet [<Book: linux>, <Book: go>, <Book: java>]>
aggregate 聚合
书的平均价格
from django.db.models import Avg,Sum,Max,Min,Count
models.Book.objects.all().aggregate(Avg(‘price‘))
每个出版社出的书和书的平均价格
from django.db.models import Count
models.Book.objects.values(‘publisher__name‘).annotate(Count(‘id‘))
models.Book.objects.values(‘publisher__name‘).annotate(Avg(‘price‘))
Q
2016或2017出版的书
q = Q(pub_date__year=‘2016‘)|Q(pub_date__year=‘2017‘)
models.Book.objects.filter(q)
<QuerySet [<Book: python>, <Book: linux>]>
F
自修改
from django.db.models import F
models.Book.objects.update(price=F(‘price‘)+10)
本表两字段比较
from datetime import timedelta
models.Book.objects.filter(pub_date__lt=F(‘pub_date‘)+timedelta(days=3))
字段迁移
from django.db.models import F
models.Book.objects.update(memo=F(‘name‘))
通过出版社查询每个出版社出了多少书
p1 = models.Publisher.objects.all()[1]
p1.book_set.all()
FORM表单
1、app01下创建文件forms.py
from django import forms from app01 import models FAVORITE_COLORS_CHOICES=( (‘blue‘,‘BLUE‘), (‘green‘,‘Green‘), (‘black‘,‘Black‘), ) BIRTH_YEAR_CHOICES = (‘1980‘,‘1981‘,‘1982‘) seat_CHOICE = ((‘1‘,‘First‘,),(‘2‘,‘Second‘,)) import re def mobile_validate(value): mobile_re = re.compile(r‘^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$‘) if not mobile_re.match(str(value)): raise forms.ValidationError(‘手机号码格式错误‘) class MailSendForm(forms.Form): sender = forms.EmailField() receiver = forms.EmailField() subject = forms.CharField(max_length=12) content = forms.CharField(widget=forms.Textarea(attrs={‘cols‘:100, ‘class‘:‘font-color‘, ‘style‘:‘background-color:lightgreen‘})) birth_year = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES)) mobile = forms.IntegerField(validators=[mobile_validate, ], error_messages={‘required‘: ‘手机不能为空‘}, widget=forms.TextInput(attrs={‘class‘: ‘form-control‘, ‘placeholder‘: ‘手机号码‘})) choice_field = forms.ChoiceField(widget=forms.Radioselect,choices=seat_CHOICE) favorite_colors = forms.MultipleChoiceField( widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES, ) def clean_sender(self):#对哪个字段做认证,就clean_xx print(‘validate sender‘,self.cleaned_data) if self.cleaned_data.get(‘sender‘) != ‘[email protected]‘: self.add_error(‘sender‘,‘only‘) return self.cleaned_data.get(‘sender‘)#不返回的话cleaned_data里面‘sender‘为None def clean(self):#所有的clean_field都验证完成后,才会执行 print(‘clean data‘,self.cleaned_data) sender = self.cleaned_data.get(‘sender‘) receiver = self.cleaned_data.get(‘receiver‘) if sender == receiver: raise forms.ValidationError(‘发送者和接受者不能相同‘) class BookForm(forms.ModelForm): class Meta: model = models.Book fields = "__all__" exclude = [‘memo‘,]
2、views.py
from django.shortcuts import render from app01.forms import MailSendForm from app01.forms import BookForm from django.views import View # Create your views here. def mail(request): if request.method == ‘POST‘: form = MailSendForm(request.POST) if form.has_changed(): print(‘form has changed‘) if form.is_valid():#验证表单数据是否合法 print(‘fuck‘,form.cleaned_data) else: print(‘error‘,form.errors) else: form = MailSendForm(initial={‘sender‘:‘[email protected]‘}) return render(request,‘mail_send.html‘,{‘form‘:form}) def book_mgr(request): if request.method == ‘POST‘: form = BookForm(data=request.POST) if form.is_valid(): form.save() form = BookForm() else: form = BookForm() return render(request,‘book.html‘,{‘form‘:form}) class BookMgr(View): form_class = BookForm template_name = ‘book.html‘ def get(self,request): print(‘get‘,request.GET) form = self.form_class() return render(request,self.template_name,{‘form‘:form}) def post(self,request): form = self.form_class(data=request.POST) if form.is_valid(): form.save() form = self.form_class() return render(request,self.template_name,{‘form‘:form})
3、mail_send.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div> <form method="post"> {% for item in form %} <div> {{ item.label }} {{ item }} {% if item.errors %} <span style="color: red"> {{ item.errors }} </span> {% endif %} </div> {% endfor %} <input type="submit" value="send"/> </form> </div> </body> </html>
modelform
form.py
class BookForm(forms.ModelForm): class Meta: model = models.Book fields = "__all__" exclude = [‘memo‘,]
view.py
def book_mgr(request): if request.method == ‘POST‘: form = BookForm(data=request.POST) if form.is_valid(): form.save() form = BookForm() else: form = BookForm() return render(request,‘book.html‘,{‘form‘:form})
以上是关于django进阶的主要内容,如果未能解决你的问题,请参考以下文章
我的C语言学习进阶之旅解决 Visual Studio 2019 报错:错误 C4996 ‘fscanf‘: This function or variable may be unsafe.(代码片段
我的C语言学习进阶之旅解决 Visual Studio 2019 报错:错误 C4996 ‘fscanf‘: This function or variable may be unsafe.(代码片段