模型类配置
from django.db import models
'''
2、完成汽车系统表模型的建立(表关系自己设计)
汽车表、汽车商家表、赞助商表、赞助商详情表
3、完成汽车系统的接口编写
汽车表:八大接口(不需要写put方法)
汽车商家表:八大接口(不需要写put方法)
'''
'''
表关系梳理:
- 汽车厂商与汽车:一对多
- 汽车与赞助商:多对多
- 赞助商与赞助商详情:一对一
'''
# 基表
class BaseModel(models.Model):
create_time = models.DateTimeField(auto_now_add=True)
is_delete = models.BooleanField(default=False)
class Meta:
abstract = True
# 汽车表
class Car(BaseModel):
name = models.CharField(max_length=255)
price = models.DecimalField(max_digits=10,decimal_places=2)
brands = models.ForeignKey(to=<span class="hljs-string">'Brand'</span>,related_name=<span class="hljs-string">'cars'</span>,db_constraint=<span class="hljs-keyword">False</span>,on_delete=models.DO_NOTHING)
sponsors = models.ManyToManyField(to=<span class="hljs-string">'Sponsor'</span>,db_constraint=<span class="hljs-keyword">False</span>,related_name=<span class="hljs-string">'cars'</span>)
@property
def brands_info(self):
return {
'name':self.brands.name,
'address':self.brands.address
}
@property
def sponsors_list(self):
sponsors_list_temp = []
sponsors = self.sponsors.all()
for sponsor in sponsors:
sponsor_dict = {'name':sponsor.name}
try:
sponsor_dict['phone'] = sponsor.detail.phone
except:
sponsor_dict['phone'] = '无'
sponsors_list_temp.append(sponsor_dict)
<span class="hljs-keyword">return</span> sponsors_list_temp
# 汽车厂商表
class Brand(BaseModel):
name = models.CharField(max_length=255)
address = models.CharField(max_length=255)
# 赞助商表
class Sponsor(BaseModel):
name = models.CharField(max_length=255)
# 赞助商详情表
class Sponsor_Detail(BaseModel):
phone = models.CharField(max_length=11)
sponsor = models.OneToOneField(to='Sponsor',db_constraint=False,on_delete=models.CASCADE,related_name='detail')
路由配置
项目主路由:
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/',include('api.urls')),
]
api、urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^v1/cars/$',views.CarsAPIView.as_view()),
url(r'^v1/cars/(?P<pk>\d+)/$',views.CarsAPIView.as_view()),
]
视图类配置
# Create your views here.
from .response import APIResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from . import models
from . import serializer
class CarsAPIView(APIView):
def get(self, request, *args, **kwargs):
'''
单查接口测试:http://127.0.0.1:8000/api/v1/cars/1/
群查接口测试:http://127.0.0.1:8000/api/v1/cars/
'''
pk = kwargs.get('pk')
if pk:
# 单查
car_obj = models.Car.objects.filter(is_delete=False, pk=pk).first()
if not car_obj:
return APIResponse(1, 'error', http_status=400)
car_ser = serializer.CarModelSerializer(car_obj)
else:
car_query = models.Car.objects.filter(is_delete=False).all()
car_ser = serializer.CarModelSerializer(car_query, many=True)
return APIResponse(results=car_ser.data)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">post</span><span class="hljs-params">(self, request, *args, **kwargs)</span>:</span>
<span class="hljs-string">'''
单增接口测试:http://127.0.0.1:8000/api/v1/cars/
- 携带数据包
{
"name":"奔驰",
"price":"6666.66",
"brands":1,
"sponsors":[1,2]
}
群增接口测试:http://127.0.0.1:8000/api/v1/cars/
- 携带数据包
[
{
"name": "宝马",
"price": "8888.88",
"brands": 1,
"sponsors": [
1
]
},
{
"name": "保时捷",
"price": "9999.99",
"brands": 2,
"sponsors": [
2
]
}
]
'''</span>
<span class="hljs-keyword">if</span> isinstance(request.data, dict):
many = <span class="hljs-keyword">False</span>
<span class="hljs-keyword">elif</span> isinstance(request.data, list):
many = <span class="hljs-keyword">True</span>
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">return</span> APIResponse(<span class="hljs-number">1</span>, <span class="hljs-string">'数据有误'</span>, http_status=<span class="hljs-number">400</span>)
car_ser = serializer.CarModelSerializer(data=request.data, many=many)
car_ser.is_valid(raise_exception=<span class="hljs-keyword">True</span>)
car_obj = car_ser.save()
<span class="hljs-keyword">return</span> APIResponse(results=serializer.CarModelSerializer(car_obj, many=many).data)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">patch</span><span class="hljs-params">(self, request, *args, **kwargs)</span>:</span>
<span class="hljs-string">'''
单改接口测试: http://127.0.0.1:8000/api/v1/cars/1/
- 携带数据包参数
{
"name":"奔驰1"
},
群改接口测试:
- 携带数据包参数
[{
"pk":1,
"name":"奔驰2"
},
{
"pk":2,
"name":"奔驰3"
}]
'''</span>
pk = kwargs.get(<span class="hljs-string">'pk'</span>)
<span class="hljs-keyword">if</span> pk:
<span class="hljs-keyword">try</span>:
car_obj = models.Car.objects.get(is_delete=<span class="hljs-keyword">False</span>,pk=pk)
<span class="hljs-keyword">except</span>:
<span class="hljs-keyword">return</span> APIResponse(<span class="hljs-number">1</span>,<span class="hljs-string">'pk error'</span>,http_status=<span class="hljs-number">400</span>)
car_ser = serializer.CarModelSerializer(instance=car_obj,data=request.data,partial=<span class="hljs-keyword">True</span>)
car_ser.is_valid(raise_exception=<span class="hljs-keyword">True</span>)
car_obj = car_ser.save()
<span class="hljs-keyword">return</span> APIResponse(results=serializer.CarModelSerializer(car_obj).data)
<span class="hljs-keyword">else</span>:
<span class="hljs-keyword">try</span>:
pks = []
<span class="hljs-keyword">for</span> dic <span class="hljs-keyword">in</span> request.data:
pks.append(dic.pop(<span class="hljs-string">'pk'</span>))
car_query = models.Car.objects.filter(is_delete=<span class="hljs-keyword">False</span>,pk__in=pks).all()
<span class="hljs-keyword">if</span> len(pks) != len(car_query):
<span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">'pk对象不存在'</span>)
<span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> e:
<span class="hljs-keyword">return</span> Response({<span class="hljs-string">'detail'</span>:<span class="hljs-string">'%s'</span>%e},status=<span class="hljs-number">400</span>)
car_ser = serializer.CarModelSerializer(instance=car_query,data=request.data,many=<span class="hljs-keyword">True</span>,partial=<span class="hljs-keyword">True</span>)
car_ser.is_valid(raise_exception=<span class="hljs-keyword">True</span>)
car_obj = car_ser.save()
<span class="hljs-keyword">return</span> APIResponse(results=serializer.CarModelSerializer(car_obj,many=<span class="hljs-keyword">True</span>).data)
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">delete</span><span class="hljs-params">(self, request, *args, **kwargs)</span>:</span>
<span class="hljs-string">'''
单删接口测试:http://127.0.0.1:8000/api/v1/cars/1/
群接口测试:http://127.0.0.1:8000/api/v1/cars/
携带数据包参数
[2,3]
'''</span>
pk = kwargs.get(<span class="hljs-string">'pk'</span>)
<span class="hljs-keyword">if</span> pk:
pks = [pk]
<span class="hljs-keyword">else</span>:
pks = request.data
<span class="hljs-keyword">try</span>:
rows = models.Car.objects.filter(is_delete=<span class="hljs-keyword">False</span>,pk__in=pks).update(is_delete=<span class="hljs-keyword">True</span>)
<span class="hljs-keyword">except</span>:
<span class="hljs-keyword">return</span> APIResponse(<span class="hljs-number">1</span>,<span class="hljs-string">'数据有误'</span>)
<span class="hljs-keyword">if</span> rows:
<span class="hljs-keyword">return</span> APIResponse(msg=<span class="hljs-string">'删除成功'</span>)
<span class="hljs-keyword">return</span> APIResponse(<span class="hljs-number">1</span>,<span class="hljs-string">'删除失败'</span>)
序列化类配置
from rest_framework import serializers
from api import models
class CarListSerializer(serializers.ListSerializer):
def update(self, instance_list, validated_data_list):
return [
self.child.update(instance_list[index],attrs) for index,attrs in enumerate(validated_data_list)
]
class CarModelSerializer(serializers.ModelSerializer):
class Meta:
list_serializer_class = CarListSerializer
model = models.Car
fields = ['name','price','brands','sponsors','brands_info','sponsors_list']
extra_kwargs = {
'brands':{
'write_only':True,
},
'sponsors':{
'write_only': True
}
}