day 93 Restframwork
苑昊博客: http://www.cnblogs.com/yuanchenqi/articles/7570003.html
一、queryset 特性
from django.db import models # Create your models here.
class Book(models.Model):
nid = models.AutoField(primary_key=True)
title = models.CharField(max_length=32)
publishDate= models.DateField()
price = models.DecimalField(max_digits=5,decimal_places=2)
keepNum= models.IntegerField()
commentNum= models.IntegerField(default=1)
# 与publish建立一对多的关系,外键字段建立在多的一方
# publish =models.ForeignKey(to="Publish",to_field="nid") #与Author表建立多对多的关系,ManytoManyFiled可以建立在两个模型中的任意一个.
# authors =models.ManyToManyField(to="Author") def __str__(self):
return self.title
from django.shortcuts import render,HttpResponse,redirect
from app01 import models # Create your views here.
def query(request): #可切片
queryset=models.Book.objects.all()
ret =queryset[0:2]
print(ret) return HttpResponse("ok")
打印结果:
<QuerySet [<Book: python>, <Book: go>]>
#可迭代
for obj in queryset:
print(obj.title,obj.price) return HttpResponse("ok")
结果:
python 1.00
go 11.00
linux 22.00
#惰性查询
queryset = models.Book.objects.all() #这一条语句没有在sql语句中执行也没有翻译成sql语句.
print(queryset) #打印了才能执行sql语句和翻译.
return HttpResponse("ok")
二 、Restframework快速实例化.
restful 一切皆资源.
from django.shortcuts import render # Create your views here.
from django.contrib.auth.models import User, Group
from app01 import models
from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups') class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name') #自定义的Book序列化
class BookSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Book
fields =('url','title') from django.contrib.auth.models import User, Group
from rest_framework import viewsets class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Group.objects.all()
serializer_class = GroupSerializer from app01 import models
class BookViewSet(viewsets.ModelViewSet):
queryset = models.Book.objects.all()
serializer_class = BookSerializer
URL
from django.conf.urls import url, include
from rest_framework import routers
from app01 import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
router.register(r'books', views.BookViewSet)
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
settings
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
'rest_framework'
]
Model表
class Book(models.Model):
title = models.CharField(max_length=32)
迁移 makemigrations and migrate .
前两个写在一个逻辑里面
books ---------------------------------get: 查询所有数据 --------------------------------- 返回的查询所有书籍.
books----------------------------------post:添加一本书籍---------------------------------返回的添加书籍
后三个写在另一一个url 逻辑里
books/1 -------------------------------get:查看某本书籍----------------------------------返回的这本书籍
books/1--------------------------------put/patch:编辑某本书籍--------------------------返回 编辑的某本书
books/1--------------------------------delete :删除某本书籍------------------------------返回空
三 、RestFramework 的 APIView.
view视图类
from django.shortcuts import render,HttpResponse,redirect # Create your views here.
from django.views import View class BookView(View):
def get(self,request): return HttpResponse("getget")
def post(self,request): return HttpResponse("postpost")
url
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/',views.BookView.as_view()),
]
model
from django.db import models # Create your models here. class Book(models.Model):
title = models.CharField(max_length=32)
settings
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
'rest_framework'
]
测试工具测试:
json实现展现 (view类下的方法)
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/',views.BookView.as_view()),
url(r"^books/(\d+)",views.BookDetailView.as_view())
from django.shortcuts import render,HttpResponse,redirect # Create your views here.
from django.views import View
from app01.models import Book
import json
class BookView(View): def get(self,request):
ret =Book.objects.all() #对queryset做序列化转换
temp=[]
for book in ret:
temp.append({
"pk":book.pk,
"title":book.title
})
return HttpResponse(json.dumps(temp))
def post(self,request): print(request) class BookDetailView(View):
pass
APIView类
apiview 下的dispatch
view(request) == return self.dispatch(request,*args,**kwargs)()
GET方法拿值
request.data
四、Restframework 的序列化组件
序列化:
views文件
from django.shortcuts import render,HttpResponse,redirect # Create your views here.
from django.views import View
from app01.models import Book
import json from rest_framework.views import APIView
from rest_framework.response import Response from rest_framework import serializers class BookSerializers(serializers.Serializer):
title =serializers.CharField(max_length=32)
price =serializers.DecimalField(max_digits=8,decimal_places=2)
publish =serializers.CharField(max_length=32,source="publish.Email")
authors =serializers.CharField(max_length=32,source="authors.all") """
#总结的源码
bs =BookSerializers(book_list,many=True)
temp=[]
for obj in book_list:
temp.append({
’titlte':obj.title,
’price':obj.price,
’publish':obj.publish.name,
'authors':obj.authors. })
#总结的源码 bs.data =json.dumps(temp) """ def get_authors(self,obj):
temp =[]
for obj in obj.authors.all():
temp.append(obj.name)
return temp class BookView(APIView): def get(self,request):
print(request._request.GET)
print(request.GET)
print(request.query_params) book_list= Book.objects.all()
# 方式一:
temp=[]
from django.forms.models import model_to_dict
# for book in book_list:
# temp.append(model_to_dict(book)) #序列化方式一 django提供的. #方式二:
# from django.core.serializers import serialize
# data =serialize("json",book_list) #序列化方式二 django提供的.
# return Response(data) #方式三:
bs =BookSerializers(book_list,many=True)
print("bs:is",bs) return Response(bs.data) def post(self,request):
print("request.data==>",request.data)
print("request.POST==>",request.POST)
return HttpResponse("post request")
class BookDetailView(View):
pass
一对多 与多对多的字段 (publish , author)
day 93 Restframwork的更多相关文章
- Entity Framework 6 Recipes 2nd Edition(9-3)译->找出Web API中发生了什么变化
9-3. 找出Web API中发生了什么变化 问题 想通过基于REST的Web API服务对数据库进行插入,删除和修改对象图,而不必为每个实体类编写单独的更新方法. 此外, 用EF6的Code Fri ...
- KBMMW 4.93.10 win64 一个BUG 修正
经常有人提到kbmmw 4.93.10 的64 位版本没有32位版本稳定. 经过官方确认,是delphi 编译器生成64 位代码内存偏移地址的错误. 在kbmMWGlobal.pas 中 有一个函数k ...
- KBMMW 4.93.10 发布
例行更新,主要是bugfix. 4.93.10 June 4 2016 Important notes (changes that may break existing code) ========= ...
- KBMMW 4.93.00 发布
可喜可敬,作者非常勤奋,跟上了delphi 10.1 的步伐. 4.93.00 April 26 2016 Important notes (changes that may break existi ...
- Centos5.8 安装 ImageMagick 6.8.9-3
下载最新的ImageMagick源码包 ImageMagick-6.8.9-3.x86_64.rpm 直接prm -ivh 安装提示错误 error: Failed dependencies: lib ...
- 重新想象 Windows 8.1 Store Apps (93) - 控件增强: GridView, ListView
[源码下载] 重新想象 Windows 8.1 Store Apps (93) - 控件增强: GridView, ListView 作者:webabcd 介绍重新想象 Windows 8.1 Sto ...
- Informatica 错误:Cannot convert from SQL type 93 to C type 4
经验和积累蛮重要!向大神学习! ---------------------------------------------------------------------- Mapping: 在sou ...
- cdoj 93 King's Sanctuary 傻逼几何题
King's Sanctuary Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/problem/sho ...
- 让人眼花缭乱的 RSS 版本0.90、0.91、0.92、0.93、0.94、1.0 和 2.0
1.0的规范 http://web.resource.org/rss/1.0/spec 2.0的规范 http://cyber.law.harvard.edu/rss/rss.html 一个介绍什么是 ...
随机推荐
- Message: u'$ is not defined' ; Stacktrace
status.html <html> <head> <meta http-equiv="content-type" content="tex ...
- 如何进入/home/user/.wine
命令行输入 :cd /home/user/.wine/drive_c/windows/fonts /home是linux的用户目录,/user是用户名/.wine是隐藏目录,凡是以.开头的都是隐藏目录 ...
- WCF生成客户端代理对象的两种方法的解释
最近在封装WCF,有一些很好的实践就记录下来,大家可以放心使用,所有代码都已经调试过.如果有高手可以大家探讨一下. 在WCF中有两种不同的方法可以用于创建客户端服务对象,他们分别为: 1. 代理构造法 ...
- 局域网代理通过wget下载
下载方法: wget -r -p -np -k http://ftp.loongnix.org/os/Fedora13-o32/RPMS/mipsel/ -r, --recursive(递归) ...
- Codeforces 677C. Coloring Trees dp
C. Coloring Trees time limit per test:2 seconds memory limit per test:256 megabytes input:standard i ...
- dedecms模型类的引入
- shift + 空格 快捷键 使输入法 在全角和半角直接切换。。 但是全角输入一个 空格 ,会造成jsp页面 无法正常解析。。比如 无法获得参数。。
shift + 空格 快捷键 使输入法 在全角和半角直接切换.. 但是全角输入一个 空格 ,会造成jsp页面 无法正常解析....比如 无法获得参数.. 如 <form action=" ...
- 学习bn算法
好处: 1.归一化后有什么好处呢?原因在于神经网络学习过程本质就是为了学习数据分布,一旦训练数据与测试数据的分布不同,那么网络的泛化能力也大大降低: 2.另外一方面,一旦每批训练数据的分布各不相同(b ...
- 2018.09.10 loj#10172. 涂抹果酱(状压dp)
传送门 三进制状压感觉有点难写啊. 不过这题状态转移方程挺简单的. 就直接f[i][j]表示前i行第i行状态为j时的选法总数,分情况转移就行了. 代码: #include<bits/stdc++ ...
- MyISAM压缩表
如果表在创建并导入数据以后,不会在进行修改操作,那么这样的表或许适合采用MyISAM压缩表. 压缩表可以极大地减少磁盘空间暂用,因此也可以减少磁盘I/O,从而提升查询性能,压缩表也支持索引.