day74
视图层
from django.shortcuts import render
from rest_framework.views import APIView
from api import models
from api import serializers
from rest_framework.response import Response
# Create your views here.
class CarsAPIView(APIView):
def get(self,request,*args,**kwargs):
car_query = models.Car.objects.filter(is_delete=False).all()
car_ser = serializers.CarModelSrealizer(instance=car_query,many=True)
car_ser.is_valid(raise_exception=True)
return Response(data={'status':0,'msg':'ok','results':car_ser.data},status=200)
from rest_framework.generics import GenericAPIView
class CarGenericView(GenericAPIView):
queryset = models.Car.objects.filter(is_delete=False).all()
serializer_class = serializers.CarModelSrealizer
def get(self,request,*args,**kwargs):
# car_query = models.Car.objects.filter(is_delete=False).all()
car_query = self.get_queryset()
# car_ser = serializers.CarModelSrealizer(instance=car_query,many=True)
car_ser = self.get_serializer(car_query,many=True)
car_ser.is_valid(raise_exception=True)
return Response(data={'status':0,'msg':'ok','results':car_ser.data},status=200)
models.py
from django.db import models
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)
price = models.DecimalField(max_digits=10, decimal_places=2)
brand = models.ForeignKey(to='Brand', db_constraint=False, null=True, on_delete=models.SET_NULL,
related_name='detail')
sponsors = models.ManyToManyField(to='Sponsor', db_constraint=False, related_name='detail')
@property
def brand_name(self):
return self.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.detail.phone
except:
sponsor_dic['phone'] = ''
sponsor_list_temp.append(sponsor_dic)
return sponsor_list_temp
def __str__(self):
return self.name
class Brand(BaseModel):
name = models.CharField(max_length=64)
def __str__(self):
return self.name
class Sponsor(BaseModel):
name = models.CharField(max_length=64)
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, blank=True)
class Meta:
verbose_name_plural = '赞助商详情'
def __str__(self):
try:
return self.sponsor.name + '的详情'
except:
return super().__str__()