1、完成汽车系统表模型的建立(表关系自己设计)
汽车表、汽车商家表、赞助商表、赞助商详情表
2、完成汽车系统的接口编写
汽车表:八大接口(不需要写put方法)
汽车商家表:八大接口(不需要写put方法
"""
related_name反查参数,设置后可以在被关联表中通过该字段反查外键所在表
on_delete:当该表中的某条数据删除后,关联外键的操作
CASCADE:这就是默认的选项,级联删除,你无需显性指定它。
PROTECT: 保护模式,如果采用该选项,删除的时候,会抛出ProtectedError错误。
SET_NULL: 置空模式,删除的时候,外键字段被设置为空,前提就是blank=True, null=True,定义该字段的时候,允许为空。
SET_DEFAULT: 置默认值,删除的时候,外键字段设置为默认值,所以定义外键的时候注意加上一个默认值。
SET(): 自定义一个值,该值当然只能是对应的实体了
如果使用两个表之间存在关联,首先db_constraint=False 把关联切断,但保留链表查询的功能,其次要设置null=True,
blank=True,注意on_delete=models.SET_NULL 一定要置空,这样删了不会影响其他关联的表
db_table 第三张表的名字
db_constraint=False,这个就是保留跨表查询的便利(双下划线跨表查询```),但是不用约束字段了,一半公司都用false,
这样就省的报错,因为没有了约束(Field字段对象,既约束,又建立表与表之间的关系)
"""
# api>urls.py
from . import views
from django.conf.urls import url
urlpatterns = [
url(r'^v1/cars/$',views.CarAPIView.as_view()),
url(r'^v1/cars/(?P<pk>d+)/$',views.CarAPIView.as_view())
]
# =============================================================================================
# views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .response import APIResponse
from . import models, serializers
class CarAPIView(APIView):
# 群查
def get(self, request, *args, **kwargs):
car_query = models.Car.objects.filter(is_delete=False).all()
car_ser = serializers.CarModelSerializer(instance=car_query, many=True)
return APIResponse(results=car_ser.data)
# =============================================================================================
# models.py
# 基表
class BaseModel(models.Model):
is_delete = models.BooleanField(default=False)
create_time = models.DateTimeField(auto_now_add=True)
class Meta:
abstract=True
# 汽车表
class Car(BaseModel):
name = models.CharField(max_length=64,verbose_name = '车名')
price = models.DecimalField(max_digits=10, decimal_places=2,verbose_name = '价格')
brand = models.ForeignKey(to='Brand',db_constraint=False,null=True,on_delete=models.SET_NULL)
sponsors = models.ManyToManyField(to='Sponsor',db_constraint=False)
@property
def brand_name(self):
return self.brand.name
@property
def sponsor_list(self):
sponsor_list_temp = []
for sponsor in self.sponsors.all():
sponsor_dic = {
'name': sponsor.name
}
try:
sponsor_dic['phone'] = sponsor.sponsordetail.phone
except:
sponsor_dic['phone'] = '未知'
sponsor_list_temp.append(sponsor_dic)
return sponsor_list_temp
class Meta:
verbose_name_plural='汽车'
def __str__(self):
return self.name
# 汽车商家表
class Brand(BaseModel):
name = models.CharField(max_length=32)
class Meta:
verbose_name_plural='汽车品牌'
def __str__(self):
return self.name
# 赞助商表
class Sponsor(BaseModel):
name = models.CharField(max_length=64)
class Meta:
verbose_name_plural='赞助商'
def __str__(self):
return self.name
# 赞助详情表
class SponsorDetail(BaseModel):
phone = models.CharField(max_length=11)
sponsor = models.OneToOneField(to=Sponsor,db_constraint=False,on_delete=models.CASCADE)
class Meta:
verbose_name_plural='赞助商详情'
def __str__(self):
try: # 连表可能会出现问题,所以要异常处理
return self.sponsor.name + '的详情'
except:
return super().__str__()
# =============================================================================================
# serializers.py
from rest_framework import serializers
from . import models
class CarModelSerializer(serializers.ModelSerializer):
class Meta:
model=models.Car
fields = ('name','price','brand_name','sponsor_list','brand','sponsors')
extra_kwargs = {
'brand': {
'required': True,
'write_only': True
},
'sponsors': {
'required': True,
'write_only': True
},
}
# =============================================================================================
# response.py
from rest_framework.response import Response
class APIResponse(Response):
def __init__(self, status=0, msg='ok', results=None, http_status=None,
headers=None, exception=False, content_type=None, **kwargs):
# 将status、msg、results、kwargs格式化成data
data = {
'status': status,
'msg': msg,
}
# results只要不为空都是数据:False、0、'' 都是数据 => 条件不能写if results
if results is not None:
data['results'] = results
# 将kwargs中额外的k-v数据添加到data中
data.update(**kwargs)
super().__init__(data=data, status=http_status, headers=headers, exception=exception, content_type=content_type)