1、整理今天所學知識點
2、新建乙個django專案,定義乙個car類,有name字串屬性,color整型選擇屬性(0:銀色,1:黑色,2:紅色,3:灰色),price全精度小數型別,image檔案型別,brand字串型別
3、基於modelserializer類,完成car資源的單查,群查,單增介面
序列化:顯示車名,車的顏色,車的**,車的海報,車的品牌
反序列化:必須提供車名,車的**,車的品牌(車的匹配需要二次確認re_brand),車的顏色預設為銀色(可以提供),車的海報不需要提供(預設為空)
# serializers.py
from rest_framework import exceptions,serializers
from django.conf import settings
from api import models
class carserializer(serializers.serializer):
name = serializers.charfield()
price = serializers.decimalfield(max_digits=8,decimal_places=2)
brand = serializers.charfield()
color = serializers.serializermethodfield()
def get_color(self,obj):
return obj.get_color_display()
img = serializers.serializermethodfield()
def get_img(self,obj):
return f""
class cardeserializer(serializers.serializer):
name = serializers.charfield()
color = serializers.integerfield(required=false)
price = serializers.decimalfield(max_digits=8, decimal_places=2,required=true)
img = serializers.imagefield(required=false)
brand = serializers.charfield(required=true)
re_brand = serializers.charfield(required=true)
def validate(self, attrs):
brand = attrs.get('brand')
re_brand = attrs.pop('re_brand')
if brand != re_brand:
raise exceptions.validationerror('兩次品牌不一致')
return attrs
def create(self, validated_data):
return models.car.objects.create(**validated_data)
# views.py
from django.shortcuts import render
from rest_framework.views import apiview
from rest_framework.response import response
from . import models,serializers
class car(apiview):
def get(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
car_obj = models.car.objects.get(pk=pk)
car_ser = serializers.carserializer(car_obj)
return response()
car_query = models.car.objects.all()
car_list_ser = serializers.carserializer(car_query,many=true)
return response()
def post(self, request, *args, **kwargs):
if not isinstance(request.data, dict) or request.data == {}:
return response()
car_obj = serializers.cardeserializer(data=request.data)
print(car_obj)
if car_obj.is_valid():
return response()
else:
return response()
# api.urls.py
from django.conf.urls import url,include
from django.contrib import admin
from django.views.static import serve
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/',include('api.urls')),
url(r'^media/(?p.*)',serve,)
]
drf 序列化器
序列化器 和 django中 的 form 和 modelform 有類似的地方 因為 在 drf 中,沒有模板的概念,所以 序列化的主要作用 是對響應的資料做序列化的,還可以對 接收到的資料做序列化 serializer 序列化 查詢的結果queryset user.objects.all ser...
drf 序列化器
models.pyclass chargepolicydetail models.model purpose c models.apartment.purpose category c models.apartment.category name models.charfield max lengt...
drf序列化元件
restful規範 前後端分離 前端乙個專案,後端乙個專案 1 通常使用https協議 2.網域名稱部署 api.baidu.com www.baidu.com api 3.版本 www.baidu.com api v2 版本號放在請求頭中 4.路徑都是名詞 可以用複數 5.根據不同的請求方式,執行...