苑昊博客: 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)