苑昊博客: 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的更多相关文章

  1. Entity Framework 6 Recipes 2nd Edition(9-3)译->找出Web API中发生了什么变化

    9-3. 找出Web API中发生了什么变化 问题 想通过基于REST的Web API服务对数据库进行插入,删除和修改对象图,而不必为每个实体类编写单独的更新方法. 此外, 用EF6的Code Fri ...

  2. KBMMW 4.93.10 win64 一个BUG 修正

    经常有人提到kbmmw 4.93.10 的64 位版本没有32位版本稳定. 经过官方确认,是delphi 编译器生成64 位代码内存偏移地址的错误. 在kbmMWGlobal.pas 中 有一个函数k ...

  3. KBMMW 4.93.10 发布

    例行更新,主要是bugfix. 4.93.10 June 4 2016 Important notes (changes that may break existing code) ========= ...

  4. KBMMW 4.93.00 发布

    可喜可敬,作者非常勤奋,跟上了delphi 10.1 的步伐. 4.93.00 April 26 2016 Important notes (changes that may break existi ...

  5. Centos5.8 安装 ImageMagick 6.8.9-3

    下载最新的ImageMagick源码包 ImageMagick-6.8.9-3.x86_64.rpm 直接prm -ivh 安装提示错误 error: Failed dependencies: lib ...

  6. 重新想象 Windows 8.1 Store Apps (93) - 控件增强: GridView, ListView

    [源码下载] 重新想象 Windows 8.1 Store Apps (93) - 控件增强: GridView, ListView 作者:webabcd 介绍重新想象 Windows 8.1 Sto ...

  7. Informatica 错误:Cannot convert from SQL type 93 to C type 4

    经验和积累蛮重要!向大神学习! ---------------------------------------------------------------------- Mapping: 在sou ...

  8. cdoj 93 King's Sanctuary 傻逼几何题

    King's Sanctuary Time Limit: 20 Sec  Memory Limit: 256 MB 题目连接 http://acm.uestc.edu.cn/#/problem/sho ...

  9. 让人眼花缭乱的 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 一个介绍什么是 ...

随机推荐

  1. BroadcastReceiver接收电量变化的广播-------在代码中动态创建接受者

    本例为动态创建广播接收者即不是在AndroidManifest.xml文件中定义的广播接收着 代码: package com.qf.broadcastreceiver01; import androi ...

  2. Golang之时间、日期类型

    孤身只影的一直小地鼠,艰难的走在路上 package main import ( "fmt" "time" ) //获取时间的格式 func testTime( ...

  3. layui学习<一>

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name ...

  4. Windows 7 手动添加受信任证书教程

    步骤如下: 1.点击开始-运行,如下图: 2.弹出"控制台"窗口如下,如下图: 3.点击"文件-添加/删除管理单元",如下图: 4.选择"证书&quo ...

  5. Mysql 查看表结构的命令

    创建数据库create database abc; 显示数据库 show databases; 使用数据库 use 数据库名; 直接打开数据库 mysql -h localhost -u root - ...

  6. 创建cookie

    cookie的创建using System;using System.Collections.Generic;using System.Linq;using System.Web;using Syst ...

  7. php 事务处理,ActiveMQ的发送消息,与处理消息

    可以通过链式发送->处理->发送...的方式处理类似事务型业务逻辑 比如 发送一个注册消息,消息队列处理完注册以后,紧接着发送一个新手优惠券赠送,赠送完再发一个其它后续逻辑处理的消息等待后 ...

  8. kafka系列 -- 多线程消费者实现

    看了一下kafka,然后写了消费Kafka数据的代码.感觉自己功力还是不够. 不能随心所欲地操作数据,数据结构没学好,spark的RDD操作没学好. 不能很好地组织代码结构,设计模式没学好,面向对象思 ...

  9. 2018.10.14 loj#6011. 「网络流 24 题」运输问题(费用流)

    传送门 费用流入门题. 直接按照题意模拟. 把货物的数量当做容量建边. 然后跑一次最小费用流和最大费用流就行了. 代码: #include<bits/stdc++.h> #define N ...

  10. 2018.07.17 牛奶模式Milk Patterns(二分+hash)

    传送门 一道简单的字符串.这里收集了几种经典做法: SAM,不想写. 后缀数组+二分,不想写 后缀数组+单调队列,不想写 hash+二分,for循哈希,天下无敌!于是妥妥的hash 代码如下: #in ...