Serializer
from rest_framework import serializers
from django.conf import settings
from . import models
class CarModelSerializer(serializers.Serializer):
re_password = serializers.CharField(min_length=3,max_length=6,write_only=True)
class Meta:
model = models.Car
fields = ('name',)
# 'colour','icon','price','brand','re_password')
extra_kwargs = {
'name':{
'min_length':3,
'max_length':8,
'error_messages':{
'min_length':'short',
'max_length':'long',
}
},
# 'colour':{
# 'read_only':True
# },
# 'color':{
# 'write_only':True
# },
}
def validate_name(self,value):
if 'g' in value.lower():
raise serializers.ValidationError('no g in name')
return value
def validate(self, attrs):
pass
view
from django.shortcuts import render
from . import models
from rest_framework.views import APIView
from rest_framework.response import Response
from . import serializers
# Create your views here.
class CarV3APIView(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 Response({
'status':1,
'msg':'pk error',
},status=400)
car_ser = serializers.CarModelSerializer(car_obj,many=False)
print('i',car_ser)
return Response({
'status':0,
'msg':'ok',
'results':car_ser.data
})
else:
car_query = models.Car.objects.filter(is_delete=False).all()
print('e',car_query)
car_ser = serializers.CarModelSerializer(car_query,many=True)
print('e',car_ser.data)
return Response({
'status':0,
'msg':'ok',
'results':car_ser.data
})