def test_get_cars(self): """Listing cars returns proper cars""" response = self.client.get('/api/cars/') data = response.data['results'] response_data = CarSerializer(data, many=True).data expected_data = CarSerializer(self.test_cars, many=True).data self.assertEqual(response_data, expected_data) self.assertEqual(response.status_code, 200)
def test_cars_filtering_by_make(self): """Filtering list of cars by make returns proper cars""" test_make = self.test_car.make response = self.client.get(f'/api/cars/?make={test_make}') data = response.data['results'] response_data = CarSerializer(data, many=True).data expected_models = [ model for model in self.test_cars if model.make.lower() == test_make.lower() ] expected_data = CarSerializer(expected_models, many=True).data self.assertEqual(response_data, expected_data) self.assertEqual(response.status_code, 200)
class OwnerSingleRideSerializer(serializers.ModelSerializer): uploader = SimpleUserSerializer(read_only=True) request = RequestsSerializer(read_only=True, many=True) car = CarSerializer() class Meta: model = Ride fields = ('pk', 'origin', 'destination', 'type', 'date', 'time', 'periodic', 'vacant_seats', 'uploader', 'request', 'car',) depth = 1 def create(self, validated_data): print('create', flush=True) return Ride.objects.create(**validated_data) def update(self, instance, validated_data): print('update', flush=True) print(validated_data, flush=True) instance.origin = validated_data.get('origin', instance.origin) instance.destination = validated_data.get('destination', instance.destination) instance.date = validated_data.get('date', instance.date) instance.time = validated_data.get('time', instance.time) instance.vacant_seats = validated_data.get('vacant_seats', instance.vacant_seats) # instance.car = validated_data.get('origin', instance.origin) car = validated_data.get('car') print(car['plate'], flush=True) instance.car = Car.objects.all().get(plate=car['plate']) instance.save() return instance
class ContractSerializer(serializers.ModelSerializer): employee = EmployeeSerializer(read_only=True) client = ClientSerializer(read_only=True) car = CarSerializer(read_only=True) payment_type_name = serializers.CharField(source='payment_type.name', read_only=True) class Meta: model = Contract fields = [ 'id', 'employee', 'client', 'car', 'date', 'payment_type', 'payment_type_name', 'price' ] def create(self, validated_data): employee = get_object_or_404(Employee.objects.all(), pk=self.context.get('employee_id')) car = get_object_or_404(Car.objects.all(), pk=self.context.get('car_id')) payment_type = get_object_or_404( PaymentType.objects.all(), pk=self.context.get('payment_type_id')) client = get_object_or_404(Client.objects.all(), pk=self.context.get('client_id')) contract = Contract.objects.create(price=validated_data.get('price'), car=car, employee=employee, payment_type=payment_type, client=client) return contract
class UserDetailSerializer(serializers.ModelSerializer): cars = CarSerializer(many=True, read_only=True) class Meta: model = CustomUser fields = ['id', 'username', 'phone', 'cars']
def create(self, request, *args, **kwargs): request_post_car_make = request.data['car_make'].upper() request_post_car_model = request.data['model_name'].capitalize() get_car_object = self.queryset.filter( model_name=request_post_car_model.lower(), car_make=request_post_car_make.lower()) if get_car_object.exists(): serializer = CarSerializer(get_car_object[0]) return Response(serializer.data, status=status.HTTP_200_OK) else: if exists(request_post_car_make, request_post_car_model): if car_validator(request_post_car_make, request_post_car_model): data = { 'car_make': request_post_car_make.upper(), 'model_name': request_post_car_model.capitalize() } serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response( {'message': 'Car make/Car model does not exists'}, status=status.HTTP_400_BAD_REQUEST) else: return Response( {'message': 'Car make and Car model name are required.'})
class UserSerializer(ModelSerializer): cars = CarSerializer(many=True, required=False) class Meta: model = UserModel fields = ['id', 'email', 'password', 'is_superuser', 'is_staff', 'is_active', 'cars'] extra_kwargs = { 'password': {'write_only': True} } def create(self, validated_data): user = UserModel.objects.create_user(**validated_data) return user
def car_list(request, format=None): if request.method == 'GET': cars = Car.objects.all() serializer = CarSerializer(cars, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CarSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class CreatRideSerializer(serializers.ModelSerializer): uploader = SimpleUserSerializer(read_only=True) car = CarSerializer() class Meta: model = Ride fields = ('pk', 'origin', 'destination', 'type', 'date', 'time', 'periodic', 'vacant_seats', 'uploader', 'car',) depth = 1 def create(self, validated_data): return Ride.objects.create(**validated_data)
def car_detail(request, pk, format=None): try: car = Car.objects.get(pk=pk) except Car.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = CarSerializer(car) return Response(serializer.data) elif request.method == 'PUT': serializer = CarSerializer(car, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': car.delete() return Response(status=status.HTTP_204_NO_CONTENT)
def post(self, request): global dict_json serializer = CarSerializer(data=request.data) # r=requests.post(url,serializer) url = 'https://vpic.nhtsa.dot.gov/api/vehicles/getmodelsformake/honda?format=json' r = requests.get(url) url_data = r.json() Data_str = json.dumps(url_data) if (request.method == 'POST'): json_data = json.dumps(request.data) dict_json = json.loads(json_data) for i in range(0, 504): if url_data['Results'][i]['Model_ID'] == int( dict_json['model_id']): serializer = CarSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(int(dict_json['model_id']), status=status.HTTP_201_CREATED) return Response("Not found Cannot add the data to the database", status=status.HTTP_400_BAD_REQUEST)
def car_list(request): if request.method == 'GET': cars = Car.objects.all() serializer = CarSerializer(cars, many=True) return Response(serializer.data, status=status.HTTP_200_OK) if request.method == 'POST': serializer = CarSerializer(data=request.data) if serializer.is_valid(raise_exception=True): #check if submitted car already exists in database if Car.objects.filter( make=serializer.validated_data['make'], model=serializer.validated_data['model']).exists(): return Response({"detail": "Car already exists in database."}, status=status.HTTP_400_BAD_REQUEST) #check if submitted car model exists at all if not car_exists(serializer.validated_data): return Response({"detail": "Car doesn't exist."}, status=status.HTTP_400_BAD_REQUEST) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED)
def get_car(self, obj): print("car") from cars.serializers import CarSerializer return CarSerializer(obj.car.all(), many=True).data