day 74 作业
day 74 作业
model
from django.db import models
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=64)
price = models.DecimalField(max_digits=10,decimal_places=2)
brands = models.ForeignKey(to='Brand',related_name='cars',db_constraint=False,on_delete=models.DO_NOTHING)
sponsors = models.ManyToManyField(to='Sponsor',db_constraint=False,related_name='cars')
@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)
return 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')
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):
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)
def post(self, request, *args, **kwargs):
if isinstance(request.data, dict):
many = False
elif isinstance(request.data, list):
many = True
else:
return APIResponse(1, '数据有误', http_status=400)
car_ser = serializer.CarModelSerializer(data=request.data, many=many)
car_ser.is_valid(raise_exception=True)
car_obj = car_ser.save()
return APIResponse(results=serializer.CarModelSerializer(car_obj, many=many).data)
def patch(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
try:
car_obj = models.Car.objects.get(is_delete=False,pk=pk)
except:
return APIResponse(1,'pk error',http_status=400)
car_ser = serializer.CarModelSerializer(instance=car_obj,data=request.data,partial=True)
car_ser.is_valid(raise_exception=True)
car_obj = car_ser.save()
return APIResponse(results=serializer.CarModelSerializer(car_obj).data)
else:
try:
pks = []
for dic in request.data:
pks.append(dic.pop('pk'))
car_query = models.Car.objects.filter(is_delete=False,pk__in=pks).all()
if len(pks) != len(car_query):
raise Exception('pk对象不存在')
except Exception as e:
return Response({'detail':'%s'%e},status=400)
car_ser = serializer.CarModelSerializer(instance=car_query,data=request.data,many=True,partial=True)
car_ser.is_valid(raise_exception=True)
car_obj = car_ser.save()
return APIResponse(results=serializer.CarModelSerializer(car_obj,many=True).data)
def delete(self, request, *args, **kwargs):
pk = kwargs.get('pk')
if pk:
pks = [pk]
else:
pks = request.data
try:
rows = models.Car.objects.filter(is_delete=False,pk__in=pks).update(is_delete=True)
except:
return APIResponse(1,'数据有误')
if rows:
return APIResponse(msg='删除成功')
return APIResponse(1,'删除失败')
ser
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
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(三):用.NET IoT库
· 上周热点回顾(1.20-1.26)