def add_address(request): serializer = AddressSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): serializer.save() request.user.addresses.add(serializer.instance) return Response(serializer.data, status.HTTP_201_CREATED) return Response(status=status.HTTP_400_BAD_REQUEST)
def update_address(request, id): try: address = request.user.addresses.get(id=id) except Address.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = AddressSerializer(address, request.data, partial=True, context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, status.HTTP_200_OK) return Response(status=status.HTTP_400_BAD_REQUEST)
def get_address(request, id): try: address = request.user.addresses.get(id=id) except Address.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) serializer = AddressSerializer(address, context={'request': request}) return Response(serializer.data, status.HTTP_200_OK)
class OrderSerializer(ModelSerializer): driver = DriverSerializer(read_only=True) user = UserSerializer(read_only=True) address = AddressSerializer(read_only=True) items = OrderItemSerializer(many=True, read_only=True) # shipping details class Meta: model = Order fields = ('id', 'user', 'store', 'order_date', 'amount', 'address', 'items', 'driver', 'status')
class TouristSpotsSerializer(ModelSerializer): attractions = AttractionsSerializer(many=True) comment = CommentsSerializer(many=True) address = AddressSerializer() fullDescription = SerializerMethodField() class Meta: model = TouristSpots fields = ('id', 'name', 'description', 'approved', 'image', 'address', 'attractions', 'comment', 'fullDescription') def get_fullDescription(self, obj): return '%s - %s' % (obj.name, obj.description)
class StoreSerializer(ModelSerializer): address = AddressSerializer(required=False) mobile = SerializerMethodField(required=False) class Meta: model = Store fields = ('id', 'name', 'about', 'owner', 'icon', 'icon', 'banner', 'address', 'categories', 'num_sales', 'mobile') read_only_fields = ['categories'] def get_mobile(self, object): return object.owner.mobile
def list_addresses(request): addresses = request.user.addresses.all() serializer = AddressSerializer(addresses, many=True, context={'request': request}) return Response(serializer.data, status.HTTP_200_OK)