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')
url
url:
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'^cars/$',views.CarsAPIView.as_view()),
url(r'^cars/(?P<pk>\d+)/$',views.CarsAPIView.as_view()),
]
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)
serializer
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
}
}